为什么我们更喜欢在 componentDidMount 中而不是在 componentWillMount 中编写标头或 api 请求或 ajax 代码。
需要与示例简单明了的区别
为什么我们更喜欢在 componentDidMount 中而不是在 componentWillMount 中编写标头或 api 请求或 ajax 代码。
需要与示例简单明了的区别
您应该使用componentDidMount()该组件,因为您需要渲染组件以便使用您从 API 获取的数据填充它。
componentWillMount(){
//Fetch API and set the State
}
render(){
return(<div>{this.state.myData}</div>)
}
componentWillMount()启动时<div>尚未渲染(目前在 DOM 中不存在)。
componentDidMount()另一方面使用时。render 方法首先运行<div>,在 DOM 中创建元素,然后componentDidMount()运行,获取数据,设置你的state并创建组件的重新渲染。这就是我们用来componentDidMount()从 API 获取数据的原因。你可以在这里找到更多信息。
警告: 您应该验证状态,以免undefined第一次渲染组件(没有来自 API 的数据)。
edgaromar90 也与构造函数相同。我们通常在初始渲染之前在构造函数和构造函数调用中设置临时状态。构造函数和 willMount 都在初始渲染之前调用,那么为什么我们不在 componentWillMount 中使用