
react的生命周期
何时 setState
不能在 mount 之前 setState,即不能在 constructor、componentWillMount 和 render 中 setState
不能在 componentWillUpdate 和 componentDidUpdate 中 setState,反复调用,栈溢出
可以在 componentDidMount 、 componentWillUnmount 和 componentWillReceiveProps 中 setState
shouldComponentUpdate
shouldComponentUpdate(nextProps, nextState)
使用 shouldComponentUpdate 以让 React 知道当前状态或属性的改变是否不影响组件的输出。默认行为是在每一次状态的改变重新渲染,在大部分情况下你应该依赖于默认行为。
在生命周期中的哪一步应该发起 AJAX 请求
需要将 AJAX 请求放到 componentDidMount 函数中执行,主要原因如下:
在 constructor 函数中不能使用 setState
在 componentWillUnmount 中无法确保在执行 render 前已经获得了异步请求的数据,componentDIdMount 不存在这个问题
为了性能的需要,FIber 有了调度 render 执行顺序的能力,所以 componentWillMount 函数的执行变得不确定了
无法保证 AJAX 请求在组件的更新阶段里成功返回数据,有可能当我们进行 setState 处理的时候,组件已经被销毁了
网友评论