javascript - 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
解决方案
为了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)
推荐阅读
- fortran - 如何在 Fortran 的代码中直接用“许多数字”设置向量的值?
- c# - 单击带有 IF 的 web 元素时如何处理 ElementClickInterceptedException
- android - 我如何在android中使用导航栏和导航图
- bash - 木偶:“错误:无法从远程服务器检索目录”将代码添加到配置文件后
- javascript - 如何解决jquery自动完成问题
- html - 如何从 tvdb 中抓取剧集编号
- react-native - 如何将边框半径应用于 Expo LinearGradient 组件的某些角
- html - .active 类在 Bootstrap 3 进度条和加载动画中不起作用
- android - 以下布局的表格格式未在 android 中显示
- javascript - 无法从 index.js 注入 html