gpt4 book ai didi

javascript - 通过对象数组和数组来 react 映射

转载 作者:行者123 更新时间:2023-12-01 00:32:57 26 4
gpt4 key购买 nike

我有如下内容:

const [channelAndReadsArray, setChannelAndReadsArray] = useState()

var channelAndReads = []
const requests = channels.map((currentChannel) => {
axios.get(serverRestAddress...
.then((result) => {
var element = {}
element.channel = currentChannel;
element.reads = result;
channelAndReads.push(element);
})
})

Promise.all(requests).then(() => {
setChannelAndReadsArray(channelAndReads)
});

...

if (!channelAndReadsArray) {
return null
})


channelAndReadsArray.map((channelAndReads) => {
console.log(channelAndReads)
})

这在控制台日志中给了我空值。我不确定这里出了什么问题

最佳答案

要使 Promise.all() 正常工作,您需要从 channels.map 返回一个 Promise。您可以返回每个元素,然后使用 Promise.all 中的列表来存储它们。

示例(未测试):

const [channelAndReadsArray, setChannelAndReadsArray] = useState()

const requests = channels.map((currentChannel) =>
axios.get(serverRestAddress)
.then((result) => ({
channel: currentChannel,
reads: result
}))
)

Promise.all(requests).then((elements) => {
setChannelAndReadsArray(elements)
});

if (!channelAndReadsArray) {
return null
})


channelAndReadsArray.map(console.log)

关于javascript - 通过对象数组和数组来 react 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com