挂载

当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:

constructor(): 在 React 组件挂载之前,会调用它的构造函数。getDerivedStateFromProps(): 在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。render(): render() 方法是 class 组件中唯一必须实现的方法。componentDidMount(): 在组件挂载后(插入 DOM 树中)立即调用。

render() 方法是 class 组件中唯一必须实现的方法,其他方法可以根据自己的需要来实现。

更新

每当组件的 state 或 props 发生变化时,组件就会更新。

当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:

getDerivedStateFromProps(): 在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。根据 shouldComponentUpdate() 的返回值,判断 React 组件的输出是否受当前 state 或 props 更改的影响。shouldComponentUpdate():当 props 或 state 发生变化时,shouldComponentUpdate() 会在渲染执行之前被调用。render(): render() 方法是 class 组件中唯一必须实现的方法。getSnapshotBeforeUpdate(): 在最近一次渲染输出(提交到 DOM 节点)之前调用。componentDidUpdate(): 在更新后会被立即调用。

render() 方法是 class 组件中唯一必须实现的方法,其他方法可以根据自己的需要来实现。

卸载

当组件从 DOM 中移除时会调用如下方法:

componentWillUnmount(): 在组件卸载及销毁之前直接调用。

以下实例初始化 state , setNewnumber 用于更新 state。在 Content 组件中的所有生命周期的显示。当点击次数大于10时,执行 componentWillUnmount 卸载操作。

class Button extends React.Component {

constructor(props) {

super(props);

this.state = {count: 0, display: true};

this.setNewNumber = this.setNewNumber.bind(this);

this.refContent = React.createRef();

}

componentDidMount() {

console.log('Button DID MOUNT!')

console.log(this.refContent.current);

}

setNewNumber() {

var display = this.state.count >= 10 ? false : true;

this.setState({count: this.state.count + 1, display: display})

}

render() {

let label = 'Content';

if(this.state.count > 8) {

label = "ContentX-" + this.state.count

}

return (

{ this.state.display &&

}

);

}

}

class Content extends React.Component {

componentWillMount() {

console.log('Component WILL MOUNT!')

}

componentDidMount() {

console.log('Component DID MOUNT!')

}

componentWillReceiveProps(newProps) {

console.log('Component WILL RECEIVE PROPS!')

}

shouldComponentUpdate(newProps, newState) {

return true;

}

componentWillUpdate(nextProps, nextState) {

console.log('Component WILL UPDATE!');

}

componentDidUpdate(prevProps, prevState) {

console.log('Component DID UPDATE!')

}

componentWillUnmount() {

console.log('Component WILL UNMOUNT!')

}

render() {

return (

{this.props.label}

{this.props.myNumber}

);

}

}

Content.defaultProps = {

label: 'Content'

};

ReactDOM.render(

,

document.getElementById('example')

);

参考阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: 


大家都在找:

react.js:react.js是什么

javascript:javascript错误怎么解决

前端:前端和后端的区别

大家都在看: