我在玩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
知道发生了什么吗?
谢谢
更换
通过
This is because doing
!previousState.questionNo
will convert the value to a boolean (mostlyfalse
) which will never be equal tothis.state.questionNo
as that is a number like1
,2
, etc