【问题标题】:Setting false to bool property in react state does nothing在反应状态下将 false 设置为 bool 属性没有任何作用
【发布时间】:2018-10-10 22:52:34
【问题描述】:

大家好,我的一个组件有一点逻辑问题,我目前正在使用 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"
        />

所以在这第一部分中,我试图将检查设置为默认值,然后是处理程序,

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

由于某种原因,第一次点击开关,我的状态对象没有改变,但开关进入关闭状态,第二次点击开关打开,状态值为 FALSE 第三次点击开关关闭,状态为真正的价值。我真的对结果感到困惑。

【问题讨论】:

  • console.log 不会总是为您提供当前状态,相反,如果您在 setState 回调中添加 console.log,它就会起作用。我的意思是:``` this.setState(state => ({//do your thing}), () => console.log()) ```
  • 真的,我的错是控制台 .log 工作正常

标签: reactjs object boolean state


【解决方案1】:

如 cmets 中所述,如果 console.log 位于 setState 之外,则它会读取旧值 - 如果将其放在该函数内,则它可以正常工作。

但这是为什么呢? 好吧,因为state updates might be asynchronous(而且 react 甚至可能批量批量更新),导致你看到旧状态

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2014-12-27
    • 2021-10-31
    相关资源
    最近更新 更多