本篇的内容大部分来自于学习https://reactjs.org/和https://www.w3schools.com/react/react_lifecycle.as的笔记
React 生命周期 = Mounting + Updating + UnMounting
Mounting: 把元素放入DOM中。
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
Updating: Component的State或者Props在改变。
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
UnMounting: 组件从DOM被移除
componentWillUnmount()
- Constructor -
constructor(props)
如果我们不初始化state,也不绑定方法,那就不用为组件实现构造函数。
一个组件在挂载之前会调用构造函数。 在为 React.Component 子类实现构造函数时,应在其他语句之前前调用 super(props)
。否则,this.props
在构造函数中可能会出现未定义的 bug。
通常,在 React 中,构造函数仅用于以下两种情况:
在 constructor()
函数中不要调用 setState()
方法。如果我们的组件需要使用内部 state,请直接在构造函数中为 this.state
赋值初始 state:
constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
只能在构造函数中直接为 this.state
赋值。如需在其他方法中赋值,你应使用 this.setState()
替代。.
要避免在构造函数中引入任何副作用或订阅。如遇到此场景,请将对应的操作放置在 componentDidMount
中.
Note
避免将 props 的值复制给 state!这是一个常见的错误:
constructor(props) { super(props); // Don't do this! this.state = { color: props.color }; }
如此做毫无必要(我们可以直接使用
this.props.color
),同时还产生了 bug(更新 prop 中的color
时,并不会影响 state)。
只有在我们刻意忽略 prop 更新的情况下使用。此时,应将 prop 重命名为 initialColor
或 defaultColor
。必要时,我们可以修改它的 key
,以强制“重置”其内部 state。比如:
class EmailInput extends Component {
state = { email: this.props.defaultEmail };
handleChange = event => {
this.setState({ email: event.target.value });
};
render() {
return <input onChange={this.handleChange} value={this.state.email} />;
}
}
出现 state 依赖 props 的情况该如何处理, 官方给出博客:避免派生状态,之后等学习到getDerivedStateFromProps() 生命周期再学习。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。