首页 > 解决方案 > React map through an array of objects and arrays

问题描述

I have something as follows:

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)
})

This is giving me null values in the console log. I am not sure what is wrong here

标签: javascriptarraysreactjs

解决方案


为了Promise.all()工作,你需要从channels.map. 您可以返回每个元素,然后使用列表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)

推荐阅读