【发布时间】: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