[嗨,我是Reactjs的新手。 我希望下面的childComponent的{this.state.data}在每次加载该组件时增加5。 所以我在静态方法getDerivedStateFromProps(props,state)下这样做 但是,第一次加载{this.state.data}时,它应该是我定义的初始值(此处为0)。 所以我期望下面的行输出从0开始递增5(我定义的初始值)
来自ClassChild的数据:{data}
预期输出:来自ClassChild的数据:0来自ClassChild的数据:5来自ClassChild的数据:10来自ClassChild的数据:15
实际输出:来自ClassChild的数据:5来自ClassChild的数据:10来自ClassChild的数据:15来自ClassChild的数据:20
反正有没有跳过第一次执行getDerivedStateFromProps(props,state),而不是在构造函数中定义-5值以获得预期的输出吗?
class ClassChild extends Component{
constructor(props){
super(props)
console.log("ClassChild constructor()")
this.state = {
data : 0
}
}
static getDerivedStateFromProps(props,state){
console.log("ClassChild getDerivedStateFromProps()")
return {
data : state.data + props.childIncState
}
}
render(){
const {count, childIncState} = this.props
const {data} = this.state
return(
<div>
<div>Count from ClassParent : {count}</div>
<div>Value to be incremented in ClassChild : {childIncState}</div>
<div>Data from ClassChild : {data}</div>
{console.log("ClassChild render()")}
</div>
)
}
}
export default ClassChild;```
您应使用componentDidUpdate()。初始渲染未调用它。
这里是一个例子:
componentDidUpdate(prevProps) {
if(prevProps.childIncState !== this.props.childIncState) {
setState({data: this.state.data + props.childIncState});
}
}