简体   繁体   中英

function returning opposite boolean value to what I expected

I have this function in my .tsx file:

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. This isn't the behaviour I expected Is there something wrong with my code?

this.setState is asynchronius. it does set the right state,but not at the moment of the call. so when you call

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

you still see the old 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. You suppose to see there the right value. (and the actual state will update with this value after all active functions traces will end)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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