这是我参与8月更文挑战的第22天,活动详情查看:8月更文挑战
首先我们来看一张图,这是新版本的生命周期图
我这个可以看到是17,现在好像已经到18了。
我们还是用上篇文章的计数器来作为例子
class Count extends React.Component {
constructor(props) {
console.log("count-constructor")
super(props)
// 初始化状态
this.state = {
count: 0
}
}
// 将要挂载
componentWillMount() {
console.log("componentWillMount")
}
//挂载完毕
componentDidMount() {
console.log("componentDidMount")
}
// +1 按钮回调
add = () => {
//获取原状态
const { count } = this.state
// 更新状态
this.setState({ count: count + 1 })
}
// 卸载组件的回调
death = () => {
ReactDOM.unmountComponentAtNode(document.getElementById('root'))
}
// 组件将要卸载调用
componentWillUnmount() {
console.log("componentWillUnmount")
}
// 控制组件更新的“阀门”
shouldComponentUpdate() {
console.log("shouldComponentUpdate")
return true
}
// 组件将要更新的钩子
componentWillUpdate() {
console.log("componentWillUpdate")
}
// 组件更新完毕的钩子
componentDidUpdate() {
console.log("componentDidUpdate")
}
force = () => {
this.forceUpdate()
}
render() {
console.log("count-render")
return (
<div>
<h1>当前求和为{this.state.count}</h1>
<button onClick={this.add}>点我+1</button>
<button onClick={this.death}>销毁</button>
<button onClick={this.force}>强制更新</button>
</div>
)
}
}
我们再看一下旧版本的生命周期图
旧版本中我们也见过这些钩子函数。那么新版本究竟差在哪里?虽然,没有影响页面
的渲染,但可以看到控制台中已经给出了警告。
警告的意思componentWillMount已经改名为UNSAFE_componentWillMount
componentWillUpdate已经改名为 UNSAFE_componentWillUpdate
忘了一个componentWillRecieveProps钩子,这个钩子是接收到props时才会触发的,所以我们再写一个子组件。并在 <Count/>
中引用 <B/>
组件
class B extends React.Component {
componentWillReceiveProps(){
console.log("componentWillReceiveProps")
}
render() {
return (
<div>我是B组件,接收到的是{this.props.carName}</div>
)
}
}
ReactDOM.render(<Count carName="BM"/>, document.getElementById('root'))
可以看到同样是有警告的(记住componentWillRecieveProps在接收到第二次props时才会打印,也就是更新时才会执行)
怎么记忆哪个钩子改名了呢?除了componentWillUnmount的其他 名字中带Will 的钩子。都需要加UNSAFE_
我们从挂载时开始对比:
卸载时:
更新时:
新版和旧版本相比 废弃了三个钩子,新增了两个钩子。这两个钩子的用法我们下一篇文章再去了解。