Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6. 生命周期 #6

Open
maxlxq opened this issue Dec 4, 2019 · 0 comments
Open

6. 生命周期 #6

maxlxq opened this issue Dec 4, 2019 · 0 comments

Comments

@maxlxq
Copy link
Owner

maxlxq commented Dec 4, 2019

  1. static defaultProps -> static propTypes -> componentWillMount -> render -> componentDidMount
  2. -props改变-> componentWillReceiveProps -state改变-> shouldComponentUpdate -> componentWillUpdate -return true-> render -> componentDidUpdate
  3. componentWillUnmount

16.+之后版本 生命周期变更

  1. render阶段 constructor -> static getDerivedStateFromProps -> shouldComponentUpdate -return true-> render
  2. Pre-commit阶段 getSnapshotBeforeUpdate
  3. commit阶段 componentDidMount -> componentDidUpdate -> componentWillUnmount

变化:
移除了componentWillReceiveProps、componentWillUpdate、componentWillMount
添加了static getDerivedStateFromProps、getSnapshotBeforeUpdate

getDerivedStateFromProps是类的静态方法,无法使用this关键字,参数为nextProps和state,返回值为对象,与state合并,更新后的state用于render,如果不需要更新,则返回null。
官方不提倡使用derived state,建议优化组件设计,如:

  1. 直接将组件拆分为完全受控组件,去掉组件的state
  2. 对于非受控组件,更新props时通过修改组件的key值,让组件重新挂载

getSnapshotBeforeUpdate 需要和 componentDidUpdate一起使用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant