我设置了一个state,然后在componentWillMount的时候调用了一个函数,这个函数里有一个fetch通过回调来修改state,但是我这里却设置不了state。请问是什么问题。如果在下面return的话,我依旧读取不到res的值
1 回答

慕勒3428872
TA贡献1848条经验 获得超6个赞
因为你是在render中使用 res.list 这个数组来渲染数据,但是在fetch结果没过来之前,res.list 是个null,所以报错了。你在初始化state的时候,把res.list设为一个空的array即可,如下:
this.state = {
res: {
list: []
}
}
还有,react在遍历数组的时候,会建议设置一个key来区分数组的每个元素,在render的时候加上key,如下:
{
res.list.map((item, index) => {
return (
<Card key={ index } >
<img .... />
</Card>
)
})
}
没有找到匹配的内容?试试慕课网站内搜索吧
添加回答
举报
0/150
提交
取消