componentWillReceiveProps
componentWillReceiveProps是React生命周期函数之一,在初始props不会被调用,它会在组件接受到新的props时调用。一般用于父组件更新状态时子组件的重新渲染。在react16.3之前,componentWillReceiveProps是在不进行额外render的前提下,响应props中的改变并更新state的唯一方式。
我的react版本是17,使用componentWillReceiveProps
已经警告了。具体使用参考下面这篇文章
React中componentWillReceiveProps的替代升级方案
查看react版本:
npm info react
getDerivedStateFromProps
getDerivedStateFromProps
是 componentWillReceiveProps
的替代方案。
类组件中使用
- 不更新状态
import { Button } from 'element-react'
import React, { Component } from 'react'
export default class test extends Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
}
changeCount() {
this.setState({
count: this.state.count + 1
})
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log(prevState)
return null
}
render() {
return (
<div>
<p>数值:{this.state.count}</p>
<Button onClick={this.changeCount.bind(this)}>点击</Button>
</div>
)
}
}
- 更新状态
import { Button } from 'element-react'
import React, { Component } from 'react'
export default class test extends Component {
constructor(props) {
super(props)
this.state = {
count: 0,
a: 0
}
}
changeCount() {
this.setState({
count: this.state.count + 1
})
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log(prevState)
return {
a: prevState.count
}
}
render() {
return (
<div>
<p>数值:{this.state.count}</p>
<p>a:{this.state.a}</p>
<Button onClick={this.changeCount.bind(this)}>点击</Button>
</div>
)
}
}
注:如果不需要更新状态,一定要返回null。一般都是监听props的改变来更新state
在函数式组件中使用
函数式组件中没有状态也没有生命周期函数,如果要监听的话需要使用useState
和 useEffect
import { Button } from "element-react";
import { useState, useEffect } from "react";
const Test1 = () => {
const [count, setCount] = useState(0)
const changeCount = () => {
setCount(count + 1)
}
useEffect(() => {
console.log(count)
}, [count])
return (
<div>
<p>数值:{count}</p>
<Button onClick={changeCount}>点击</Button>
</div>
)
}
export default Test1;
注:
1、多个依赖项与某一个状态有关
useEffect(() => {
console.log(count)
}, [count,sum])
多个依赖项时,只要有一个依赖改变都会触发该副作用。例如有状态a、b、c三个状态,无论a改变还是b改变,状态c都要改变
2、多个依赖没有关联,这时可以写多个useEffect
useEffect(() => {
console.log("count", count)
}, [count])
useEffect(() => {
console.log("sum", sum)
}, [sum])