Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 将false设置为处于react状态的bool属性没有任何作用_Reactjs_Object_Boolean_State - Fatal编程技术网

Reactjs 将false设置为处于react状态的bool属性没有任何作用

Reactjs 将false设置为处于react状态的bool属性没有任何作用,reactjs,object,boolean,state,Reactjs,Object,Boolean,State,大家好,我的一个组件有点逻辑问题,我现在使用的是react开关 <Switch onChange={e => this.handleSwitch(e, 'spaces', 'living')} checked={this.state.dwelling.spaces.living === undefined ? true : this.state.dwelling.spaces.living} id

大家好,我的一个组件有点逻辑问题,我现在使用的是react开关

        <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"
        />

由于某些原因,在第一次单击开关时,“我的状态”对象没有更改,但开关处于关闭状态,第二次单击开关处于打开状态,值为FALSE的状态第三次单击开关处于关闭状态,值为true的状态。我真的对结果感到困惑。

如注释中所述,
控制台.log
如果在
设置状态
之外,则会读取旧值-如果将其放在该函数内部,则工作正常

但为什么呢?
好吧,因为(而且react甚至可能会批处理多个批处理更新),导致您看到旧状态

console.log不会总是给您当前状态,相反,如果您在setState回调中添加console.log,那么它就会工作。我的意思是:``this.setState(state=>({//do your thing}),()=>console.log())```真的,我的错,都是关于console.log的,它工作得很好
 handleSwitch(e, type, subtype) {
    this.setState(
        state => ({
            dwelling: {
                ...state.dwelling,
                [type]: {...state.dwelling[type], [subtype]: e}
            }
        })
    );
    console.log(this.state.dwelling.spaces);
}