简体   繁体   English

function 返回与我预期相反的 boolean 值

[英]function returning opposite boolean value to what I expected

I have this function in my .tsx file:我的.tsx文件中有这个 function:

doIsChecked() {
    var isItChecked = document.getElementById('isPless') as HTMLInputElement;

    console.log('updateDocsFlag before: ' + this.state.updateDocsFlag);
    if (isItChecked.checked) {
        this.setState({ updateDocsFlag: true });
    } else {
        this.setState({ updateDocsFlag: false });
    }
    console.log('updateDocsFlag after: ' + this.state.updateDocsFlag);
}

It get called when a checkbox is ticked/unticked.当复选框被勾选/未插入复选框时,它会被调用。 I noticed that if isItChecked is true updateDocsFlag is false as can be seen in the before and after log entries.我注意到如果isItChecked为 true updateDocsFlag为 false,可以在日志条目之前和之后看到。 This isn't the behaviour I expected Is there something wrong with my code?这不是我预期的行为我的代码有问题吗?

this.setState is asynchronius. this.setState是异步的。 it does set the right state,but not at the moment of the call.它确实设置了正确的 state,但不是在通话时。 so when you call所以当你打电话时

    console.log('updateDocsFlag after: ' + this.state.updateDocsFlag);

you still see the old state.您仍然可以看到旧的 state。 try to do following:尝试执行以下操作:

doIsChecked() {
    var isItChecked = document.getElementById('isPless') as HTMLInputElement;

    console.log('updateDocsFlag before: ' + this.state.updateDocsFlag);
    let updateDocsFlag = isItChecked.checked;
    this.setState({ updateDocsFlag });
    console.log('updateDocsFlag after: ' + updateDocsFlag);
}

this way you log not the state, but the value you passing into the state.这样,您记录的不是 state,而是您传递给 state 的值。 You suppose to see there the right value.你想在那里看到正确的价值。 (and the actual state will update with this value after all active functions traces will end) (在所有活动功能跟踪结束后,实际的 state 将使用此值更新)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM