我试图通过使用这样的嵌套属性来组织我的状态:

this.state = {
   someProperty: {
      flag:true
   }
}

但是像这样更新状态,

this.setState({ someProperty.flag: false });

是行不通的。怎样才能正确地做到这一点呢?


当前回答

有很多库可以提供帮助。例如,使用immutability-helper:

import update from 'immutability-helper';

const newState = update(this.state, {
  someProperty: {flag: {$set: false}},
};
this.setState(newState);

使用lodash/fp设置:

import {set} from 'lodash/fp';

const newState = set(["someProperty", "flag"], false, this.state);

使用lodash/fp合并:

import {merge} from 'lodash/fp';

const newState = merge(this.state, {
  someProperty: {flag: false},
});

其他回答

const newState = Object.assign({}, this.state);
newState.property.nestedProperty = "new value";
this.setState(newState);

对于在2022年读书的人来说:

    constructor(props) {
        super(props);
        this.state = {
            someProperty: {
                flag: true
            }
            otherValues: '',
            errors: {}
        };

        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;
        const someProperty = { ...this.state.someProperty };
        someProperty[name] = value;

        this.setState({
            someProperty: someProperty
        });
    }
    .......

试试下面的代码:

this.setState({ someProperty: {flag: false} });

这显然不是正确或最好的方法,但在我看来,这是更清晰的:

this.state.hugeNestedObject = hugeNestedObject; 
this.state.anotherHugeNestedObject = anotherHugeNestedObject; 

this.setState({})

然而,React本身应该迭代思想嵌套对象,并相应地更新状态和DOM。

使用箭头函数代替,这应该做的把戏。

setItems((prevState) => {
   prevState.nestedData = newNestedData;
   prevState.nestedData1 = newNestedData1;
});

不要忘记使用箭头函数(prevState) =>{更新js赋值语句…}