Reactjs 将false设置为处于react状态的bool属性没有任何作用
大家好,我的一个组件有点逻辑问题,我现在使用的是react开关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
<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);
}