【问题标题】:React map through an array of objects and arrays通过对象和数组的数组反应映射
【发布时间】:2019-10-12 09:00:02
【问题描述】:

我有以下几点:

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

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

【问题讨论】:

  • 请修复代码以使其成为minimal reproducible example 或至少是有效的语法。
  • .map() 回调中没有返回任何内容
  • 那是因为,axios 调用是异步的。循环将在单个 http 调用成功之前完成,因此您的 console.log 将没有任何内容。您需要等到所有 api 都成功。channelAndRead 中将没有任何值,因为 console.log 执行时不会推送任何内容。
  • @Panther “那是因为,axios 调用是异步的...” - 不,因为 TO“等待”Promise.all(requests) 的结果。问题是.map() 中缺少return
  • 如果你认为它等待然后它等待,但我看到没有等待或控制台通过回调调用以查看它正在等待..但如果你这么说..是的:-/

标签: javascript arrays reactjs


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-11-21
      • 1970-01-01
      • 2020-07-29
      • 2020-10-31
      • 2023-03-18
      • 2019-01-07
      • 2019-02-09
      • 1970-01-01
      相关资源
      最近更新 更多