3 回答
TA贡献1869条经验 获得超4个赞
此问题的原因setState()是异步的。在您的情况下,这意味着状态已在此处进行更改:
this.setState({data: data, loading: false });
在随后的调用this.setValues();(它本身依赖于data组件状态中定义的对象)上不是立即可观察到的。这些情况的解决方案是在setState()方法上使用第二个回调参数来运行依赖于相应状态更改的逻辑:
/* The state change will be observable when setValues() is called via
the callback */
this.setState({data: data, loading: false }, () => {
this.setValues();
});
至于你的组件实现的建议,考虑修改render()方法,这样day,open和higher被访问和渲染render()直接,因为你似乎是做,而不是在其他地方缓存这些值。所以尝试这样的事情:
render() {
this.fetch_data();
if(this.state.loading || !this.state || !this.state.data) {
return <div>Loading :D...</div>
} else {
/* Call to setValues() no longer needed */
const day = this.state.data["Meta Data"]["3. Last Refreshed"];
const open = this.state.data["Time Series (Daily)"][day]["1. open"];
const higher = this.state.data["Time Series (Daily)"][day]["2. high"];
return (
<div>
<h2>Symbol: {symbol}</h2>
<p>Url: {url}</p>
<ul>
<li>
Open price: {open}
</li>
<li>
Higher price: {higher}
</li>
</ul>
</div>
);
}
}
添加回答
举报