我正在尝试获取一些数据并在渲染方法上显示:
constructor(props) {
super(props);
this.state = {
job: {}
}
}
componentDidMount() {
fetch(API_URL).then((res) => res.json()).then((res) => this.setState({ job: res.job }));
}
render() {
return (<Text>{this.state.job.name}</Text>)
}
但是当屏幕加载并且我尝试访问作业名称时发生异常:
未定义不是对象
如何从 API 获取数据并正确渲染? 谢谢。
最佳答案
由于 fetch
是异步的,您的 View 将尝试渲染并寻找尚不存在的 name
。如果您愿意,您可以在 render
方法中设置 Loading...
状态,如下所示 -
render() {
if (!this.state.job.name) {
return (
<div>Loading...</div>
);
}
return (<Text>{this.state.job.name}</Text>);
}
关于javascript - React Native fetch 和 componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45190693/