簡體   English   中英

通過對象數組和 arrays 反應 map

[英]React map through an array of objects and arrays

我有如下內容:

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

這在控制台日志中給了我 null 值。 我不確定這里有什么問題

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM