static getDerivedStateFromProps()git
当本地state
须要根据props
来改变的时候可调用此方法。github
这个方法是在render()
前会被执行,只要执行render()
都会被在以前被触发。web
该方法有两个参数props
和state
; 返回值为state
对象, 不须要返回总体state
,把须要改变的state
返回便可。性能优化
示例:dom
static getDerivedStateFromProps(props, state) { if(props.color !== state.color) { return {color: props.color}; } }
shouldComponentUpdate()函数
此方法有两个参数:shouldComponentUpdate(nextProps, nextState)
.性能
返回值为true
或者false
, 默认返回true
.优化
主要使用它来控制组件要不要渲然,经常使用做性能优化。this
触发此方法的条件是:组件接收任意props
或者state
时都会被调用。须要注意的是在第一次render()
时和在调用forceUpdate()
时都不会被触发。code
示例:
shouldComponentUpdate(nextProps, nextState) { if(nextProps.color !== this.props.color || nextState.size !== this.state.size) { return true; } return false; }
render()
这个方法是React组件中必需要提供的方法。当state
或者props
任一数据有更新时都会执行。
须要注意当继承PureComponent
时,不会对对象进行深度比较,也就是,不会根据对象内的对象变化时执行render()
.
render()
是一个纯函数,也就是不能在这个方法中有相似setState()
这样的行为。
返回的数据类型能够有:
null
、String
、Number
、Array
、Boolean
。Portal
注意:不能返回
undefined
.
当shouldComponentUpdate()
返回false
时,不管state
和props
有没有变化,这个方法都不执行。
示例:
render() { return ( <div>{this.state.color}</div> ); }
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; } }
componentWillUnmount()
在组件被卸载或者销毁的时候执行,方法中不能再有setState
的动做。
通常用做清除组件中起的定义器、webSocket
等。
示例:
componentWillUnmount() { if(this.timer) { window.clearInterval(this.timer); this.timer = null; } }
componentDidCatch()
componentDidCatch(error, info)
异常的处理。
只能捕获组件树的异常,没法捕获这个方法内的异常。
示例:
定义一下异常处理组件:
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { this.setState({ hasError: true }); window.console.log(error, info); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
使用这个异常组件:
<ErrorBoundary> <MyWidget /> </ErrorBoundary>
推荐阅读《React 手稿》