本篇的内容大部分来自于学习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 中,构造函数仅用于以下两种状况:
- Initializing: 通过给
this.state
赋值对象来初始化外部 state。 - Binding: 为事件处理函数绑定实例
在 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() 生命周期再学习。