React16生命周期

作者 : 开心源码 本文共1634个字,预计阅读时间需要5分钟 发布时间: 2022-05-13 共298人阅读

react生命周期,先上官网的图

react16生命周期.png

关于各生命周期函数的参数、返回值以及何时执行,啥也不说了,上代码,自己跑一边就啥都明白了。

//组件class Testlifecycles extends React.Component {  constructor(props) {    super(props);    console.log('constructor');    this.handleClick = this.handleClick.bind(this);    this.state = {b: 1};    // getDefaultProps:接收初始props    // getInitialState:初始化state  }  static getDerivedStateFromProps(props, state) {    console.log('getDerivedStateFromProps', props, state);    // 组件每次被rerender的时候,包括在组件构建之后(虚拟dom之后,实际dom挂载之前),每次获取新的props或者state之后;;每次接收新的props之后都会返回一个对象作为新的state,返回null则说明不需要升级state    return state;  }  componentDidCatch(error, info) {    console.log('componentDidCatch', error, info);    // 获取到javascript错误  }  handleClick() {    this.props.parentClick();  }  render() {    return <h2 onClick={this.handleClick}>点击试一下,a:{this.props.a}</h2>;  }  componentDidMount() {    console.log('componentDidMount');    // 挂载后  }  shouldComponentUpdate(nextProps, nextState) {    console.log('shouldComponentUpdate', nextProps, nextState);    // 组件Props或者者state改变时触发,true:升级,false:不升级    return true;  }  getSnapshotBeforeUpdate(prevProps, prevState) {    console.log('getSnapshotBeforeUpdate', prevProps, prevState);    // 组件升级前触发    return null;  }  componentDidUpdate() {    console.log('componentDidUpdate');    // 组件升级后触发  }  componentWillUnmount() {    console.log('componentWillUnmount');    // 组件卸载时触发  }}//在App中调用Testlifecycles组件class App extends React.Component {  constructor(props) {    super(props);    this.state = {a: 1};  }  parentClick() {    this.setState({a: 2});  }  render() {    let x;    if (this.state.a === 1) {      x = (        <Testlifecycles          parentClick={() => this.parentClick()}          a={this.state.a}        />      );    } else {      x = <div>estlifecycles组件被卸载</div>;    }    return <div>{x}</div>;  }}//将App挂载到根节点下ReactDOM.render(<App />, document.getElementById('root'));

参考资料:
生命周期图谱
React.Component
React-新的生命周期(React16版本)

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » React16生命周期

发表回复