为什么我们更喜欢在componentDillMount中不在componentWillMount中编写头或api请求或ajax代码

时间:2017-08-24 18:29:55

标签: reactjs react-lifecycle

为什么我们更喜欢在componentDillMount中编写header或api请求或ajax代码而不是在componentWillMount中。

需要与示例

简单明了的区别

2 个答案:

答案 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)

edgaromar90与构造函数的情况相同。我们通常在构造函数中设置临时状态,并在初始渲染之前调用构造函数。 constuctor和willMount都会在初始渲染之前调用,那么我们为什么不在componentWillMount中使用