通过对象和数组数组来反应地图

时间:2019-10-12 09:00:02

标签: javascript arrays reactjs

我有以下内容:

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

这使控制台日志中的值为空。 我不确定这是怎么回事

2 个答案:

答案 0 :(得分:2)

要使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)

答案 1 :(得分:0)

request数组将为空,因为您没有从.map返回任何内容,因此一种更干净的方法是不使用异步代码推送到数组中

const [channelAndReadsArray, setChannelAndReadsArray] = useState();
const requests = channels.map(async (currentChannel) => {
           return axios.get(serverRestAddress...)
           .then((result) => {
                var element = {}
                element.channel= currentChannel;
                element.reads= result;
                return result;
             })
           });
Promise.all(requests).then((results) => { setChannelAndReadsArray(results)});

if (!channelAndReadsArray) {
     return null
});
channelAndReadsArray.map((channelAndReads)=>{
     console.log(channelAndReads)
});