【发布时间】:2020-01-16 08:05:38
【问题描述】:
我是新手,尝试在 React JS 中获取 JSON 数据,但收到此错误:
TypeError: Cannot read property 'data' of null
我的代码是:
import React from 'react';
export default class FetchJson extends React.Component {
componentDidMount()
{
fetch('https://api.myjson.com/bins/9i63i')
.then((response) => response.json())
.then((findresponse) =>{
this.setState({ data: findresponse })
//console.log(this.state.data);
//console.log(findresponse.DesignName);
})
}
render() {
return(
<ul>
{this.state.data.map((x,i) => <li key={i}>{x.DesignName}</li>)}
</ul>
);
}
}
你可以在这里看到json数据:http://myjson.com/9i63i
我想检索键DesignName 的值,即part1,这没有发生。
请参阅注释行:两者都给了我价值。但是当我尝试在渲染内的返回方法中访问它时。我收到错误:TypeError: Cannot read property 'data' of null 在这一行:
{this.state.data.map((x,i) => <li key={i}>{x.DesignName}</li>)}
如何解决?
【问题讨论】:
-
可能是因为
render()在你之前运行.then()回调已设置状态(因为这是异步发生的)。在尝试映射之前检查this.state是否已定义:{this.state && this.state.data.map((x,i)...}