【发布时间】:2018-10-31 09:08:59
【问题描述】:
我正在使用 reactJS 16.5.2 并且我对下一个主要版本 (17) 有点困惑,其中组件 LiceCycle 的一些经典方法将被弃用(componentWillReceiveProps、componentWillUpdate 和 componentWillMount)。
关注此帖:https://medium.com/@baphemot/understanding-reactjs-component-life-cycle-823a640b3e8d
我正在努力做好准备,但我找不到正确的位置在我的组件中进行 AjaxCall 以填充组件本身的数据。
我通常制作一个包装器组件来管理与外部服务器的异步通信。
组件通常在 setState 为合法的 componentWillMount 中调用该方法。
componentWillMount()
{
this.props.someAjaxCall(); //calling the Wrapped method that will call a setDate( { ajaxData : response.data } );
}
renderData()
{
if (this.props.ajaxData === undefined) //ajax call is not ended yet
{
return <span> No data </span>
}
return <span> Lot of Data </span> //ajax call has completed
}
render()
{
return this.renderData();
}
使用此流程,组件将被渲染两次。第一次没有填充 ajaxData,因此将呈现“无数据”。 在 AjaxCall 结束时,包装器将创建一个 setState,以便调用新的渲染。
在这个流程中,我通常使用 shouldComponentUpdate 来避免对任何包装组件进行不必要的渲染。
问题是。随着 componentWillMount 的弃用,我必须在哪里调用 Ajax 异步方法?
【问题讨论】:
-
有理由不把调用放在构造函数中吗?
-
componentDidMount通常是从中获取数据的生命周期钩子
标签: javascript ajax reactjs