ComponentDidUpdate中的怪异条件行为

我在玩javascript并做出反应时遇到了一个奇怪的情况。

async componentDidUpdate(previousProps, previousState) {
    console.log(previousState.questionNo,this.state.questionNo);
    console.log(!previousState.questionNo === this.state.questionNo)
    if (!previousState.questionNo === this.state.questionNo) {
            console.log("I'm here")
            const index = Math.floor(Math.random() * 12); //12 is hardcoded i need to find sth better later
            const resp = await questionsApi.get(`/questions/${index}`);
            this.setState({ question: resp.data });
        }
    }

And when i check in console eventhough values are not equal component did not rendered. And also in console console.log(!previousState.questionNo === this.state.questionNo) awkwardly always provides false.

控制台输出如下:

1 1 Component.js:16
false Component.js:17
1 2 Component.js:16
false component.js:17

知道发生了什么吗?

谢谢

评论
  • 寂寞B
    寂寞B 回复

    更换

    if (!previousState.questionNo === this.state.questionNo)
    

    通过

    if (previousState.questionNo !== this.state.questionNo)
    

    This is because doing !previousState.questionNo will convert the value to a boolean (mostly false) which will never be equal to this.state.questionNo as that is a number like 1, 2, etc