我有这个getData方法从外部API中获取一些统计信息:
getData = (name=this.state.name) => {
console.log('Name', name);
fetch(`https://api.coinmarketcap.com/v1/ticker/${name}/?convert=USD`)
.then(res => res.json())
.then(results => {
this.setState ({
marketdata: results[0]
})
})
}
如果我控制台记录结果[0],它看起来像这样:
{id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "10908.7", …}
如果我尝试渲染其中一个值:
<p>{marketdata.price_usd}</p>
页面将加载 - 我可以看到页面上的实际值,然后错误点击屏幕:
Cannot read property 'price_usd' of undefined
这可能与我如何使用生命周期方法有关吗?
componentWillReceiveProps(nextProps) {
if(this.props.value !== nextProps.value) {
this.setState({value: nextProps.value });
}
}
componentDidMount() {
const {value, name} = this.state;
this.getName(value);
this.getData(name);
}
componentDidUpdate(prevProps, prevState) {
if(this.state.value !== prevProps.value) {
this.getName(this.state.value);
}
if(this.state.name !== prevState.name) {
this.getData(this.state.name);
}
}