wormIT 2019-06-25
了解React组件的生命周期
React流程状态图
注意:流程状态图为使用React.createClass方法的生命周期
ajax获取后台数据渲染时,一般将调用ajax方法放在componentDidMount中,这样可以先渲染虚拟dom再展示数据,当再次调用ajax数据改变时,dom内数据会再次渲染,而不用再次加载整个dom。如果在该dom要根据条件只通过ajax获取一次数据,则可以将调用ajax的方法放在componentWillMount。jQuery,异步请求也可以使用fetch等componentWillUpdate中,尽量避免使用setState()或setProps()方法。若无条件判断情况下使用setState()或setProps(),会导致死循环,同样componentDidUpdate中使用setState()若无条件限制也会导致死循环。shouldComponentUpdate可以对是否进行渲染的条件判断,能够作为性能调优的手段,避免无意义渲染。componentWillReceiveProps可以通过nextProps获取新传入的参数值,例如:nextProps.operationType获取operationTypesetState()的周期为:componentWillMount、componentDidMount、componentWillReceiveProps、componentDidUpdatethis.state的值通过构建列表树后总结补充:
setState不会立即生效,要经过render过程才能真正改变state值return时调用方法setState,会引起shouldComponentUpdate周期,而此时componentDidMount周期已完成。React组件生命周期过程说明
React组件生命周期
React数据获取为什么一定要在componentDidMount里面调用?