在反应状态下将false设置为bool属性不会做任何事情

时间:2018-04-30 19:57:24

标签: reactjs object boolean state

大家好,我的一个组件有一点逻辑问题,我目前正在使用react-switch

        <Switch
            onChange={e => this.handleSwitch(e, 'spaces', 'living')}
            checked={this.state.dwelling.spaces.living === undefined ? true : this.state.dwelling.spaces.living}
            id="normal-switch"
            onColor="#86d3ff"
            onHandleColor="#2693e6"
            handleDiameter={20}
            uncheckedIcon={false}
            checkedIcon={false}
            boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
            activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)"
            height={15}
            width={38}
            className="react-switch"
        />

所以在第一部分我试图设置为默认值为checked的真值,然后是处理程序,

 handleSwitch(e, type, subtype) {
    this.setState(
        state => ({
            dwelling: {
                ...state.dwelling,
                [type]: {...state.dwelling[type], [subtype]: e}
            }
        })
    );
    console.log(this.state.dwelling.spaces);
}

由于某种原因点击开关,我的状态对象不会改变,但是开关进入关闭状态,第二次点击开关变为ON,状态值为FALSE第三次点击开关关闭并进入状态真实的价值。我对结果感到很困惑。

1 个答案:

答案 0 :(得分:0)

正如评论中所提到的,如果console.log位于setState之外,#!/bin/bash # saved as mov_dir.sh cd ~/mt/v3/rt_linux-rt-tools/ bash 会读取旧值 - 如果将其置于该函数内,则可以正常工作。

但为什么呢? 好吧,因为state updates might be asynchronous(并且反应可能甚至批量多次批量更新),导致您看到旧状态

相关问题