组件更新
static getDerivedStateFromProps()
shouldComponentUpdate()
此方法有两个参数:
shouldComponentUpdate(nextProps, nextState).返回值为
true或者false, 默认返回true.主要使用它来控制组件要不要渲然,常用作性能优化。
触发此方法的条件是:组件接收任意
props或者state时都会被调用。需要注意的是在第一次render()时和在调用forceUpdate()时都不会被触发。示例:
shouldComponentUpdate(nextProps, nextState) { if(nextProps.color !== this.props.color || nextState.size !== this.state.size) { return true; } return false; }render()
getSnapshotBeforeUpdate()
getSnapshotBeforeUpdate(prevProps, prevState)在render将组件渲然到dom中就会执行。如果不实现该方法则返回null.
返回的数据由自己定义,并且返回的数据作为
componentDidUpdate方法中的参数。示例:
class ScrollingList extends React.Component { constructor(props) { super(props); this.listRef = React.createRef(); } getSnapshotBeforeUpdate(prevProps, prevState) { if (prevProps.list.length < this.props.list.length) { const list = this.listRef.current; return list.scrollHeight - list.scrollTop; } return null; } render() { return ( <div ref={this.listRef}>{/* ...contents... */}</div> ); } }componentDidUpdate()
该方法在组件更新后立即执行,并且在组件挂载阶段不执行。
componentDidUpdate(prevProps, prevState, snapshot)第三个参数就是上节中提到的。示例:
componentDidUpdate(prevProps, prevState, snapshot) { if (snapshot !== null) { const list = this.listRef.current; list.scrollTop = list.scrollHeight - snapshot; } }