为什么我们更喜欢在componentDillMount中编写header或api请求或ajax代码而不是在componentWillMount中。
需要与示例
简单明了的区别答案 0 :(得分:1)
您应该使用 componentDidMount()
,因为您需要呈现该组件,以便使用您从API中提取的数据填充该组件。
componentWillMount(){
//Fetch API and set the State
}
render(){
return(<div>{this.state.myData}</div>)
}
当componentWillMount()
启动时,<div>
尚未呈现(目前在DOM中不存在)。
另一方面使用componentDidMount()
时。 render方法首先在DOM中创建<div>
元素,之后运行componentDidMount()
,获取数据,设置state
并创建组件的重新渲染。这就是我们使用componentDidMount()
从API获取数据的原因。您可以找到更多信息here。
警告: 您应该验证状态,这样您第一次渲染组件时就不会得到undefined
(没有来自API)。
答案 1 :(得分:0)