react的state和componentWillMount

我设置了一个state,然后在componentWillMount的时候调用了一个函数,这个函数里有一个fetch通过回调来修改state,但是我这里却设置不了state。请问是什么问题。

https://img2.mukewang.com/5bf669aa0001ba4205710394.jpg

https://img.mukewang.com/5bf669b30001621601590035.jpg

如果在下面return的话,我依旧读取不到res的值

https://img3.mukewang.com/5bf669c50001333b05620405.jpg

https://img.mukewang.com/5bf669d200013f1c06580417.jpg

米脂
浏览 974回答 1
1回答

慕勒3428872

因为你是在render中使用 res.list 这个数组来渲染数据,但是在fetch结果没过来之前,res.list 是个null,所以报错了。你在初始化state的时候,把res.list设为一个空的array即可,如下:this.state = {&nbsp; &nbsp; res: {&nbsp; &nbsp; &nbsp; &nbsp; list: []&nbsp; &nbsp; }}还有,react在遍历数组的时候,会建议设置一个key来区分数组的每个元素,在render的时候加上key,如下:{&nbsp; &nbsp; res.list.map((item, index) => {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Card key={ index } >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img .... />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Card>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; })}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript