getDerivedStateFromProps 不更新状态?

时间:2021-05-08 08:44:50

标签: javascript reactjs getderivedstatefromprops

我有这个场景:

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 不应该更新状态吗?

1 个答案:

答案 0 :(得分:0)

好的,我现在很快意识到错误。要在 shouldComponentUpdate 中使用更新的状态,您必须使用参数 shouldComponentUpdate(nextProps, nextState) 而不是 this.state