问题描述
我有这个场景:
static getDerivedStateFromProps(nextProps,prevstate) {
if(...) {
console.log("A")
return {
a: true
}
}
console.log("B")
return {
a: false
}
}
shouldComponentUpdate() {
const { a } = this.state
console.log(a)
return a
}
现在运行这个我得到
A
false
那么我在这里错过了什么? getDerivedStateFromProps 不应该更新状态吗?
解决方法
好的,我现在很快意识到错误。要在 shouldComponentUpdate
中使用更新的状态,您必须使用参数 shouldComponentUpdate(nextProps,nextState)
而不是 this.state
。