react 重点知识
组件的生命周期
当首次装载组件时,按顺序执行
- getDefaultProps ( 默认属性 )
- getInitialState ( 默认状态机 )
- componentWillMount (服务器端和客户端都只调用一次,在初始化渲染执行之前立刻调用。如果在这个方法内调用 setState,render() 将会感知到更新后的 state,将会执行仅一次,尽管 state 改变了。)
- render
- componentDidMount
当卸载组件时
- componentWillUnmount
当重新装载组件时
- getInitialState
- componentWillMount
- render
- componentDidMount
- 但并不执行 getDefaultProps
当再次渲染组件时,组件接受到更新状态,此时按顺序执行
- componentWillReceiveProps
在组件接收到新的 props 的时候调用 componentWillReceiveProps(object nextProps) 列子:componentWillReceiveProps(nextProps) { this.setState({ value: nextProps.value }); }
- shouldComponentUpdate
在接收到新的 props 或者 state,将要渲染之前调用。该方法在初始化渲染的时候不会调用,在使用 forceUpdate 方法的时候也不会。 如果确定新的 props 和 state 不会导致组件更新,则此处应该 返回 false。
shouldComponentUpdate: function(nextProps, nextState) { return nextProps.id !== this.props.id; }
如果 shouldComponentUpdate 返回 false,则 render() 将不会执行,直到下一次 state 改变。(另外,componentWillUpdate 和 componentDidUpdate 也不会被调用。) 默认情况下,shouldComponentUpdate 总会返回 true,在 state 改变的时候避免细微的 bug,但是如果总是小心地把 state 当做不可变的,在 render() 中只从 props 和 state 读取值,此时你可以覆盖 shouldComponentUpdate 方法,实现新老 props 和 state 的比对逻辑。 如果性能是个瓶颈,尤其是有几十个甚至上百个组件的时候,使用 shouldComponentUpdate 可以提升应用的性能。
- componentWillUpdate
在接收到新的 props 或者 state 之前立刻调用。在初始化渲染的时候该方法不会被调用。 使用该方法做一些更新之前的准备工作。
注意: 你不能在该方法中使用 this.setState()。如果需要更新 state 来响应某个 prop 的改变,请使用 componentWillReceiveProps。
- render
- componentDidUpdate