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

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

但是像这样更新状态,

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

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


当前回答

你应该把new state传递给setState。 新状态的引用必须与旧状态的引用不同。

所以试试这个:

this.setState({
    ...this.state,
    someProperty: {...this.state.someProperty, flag: true},
})

其他回答

我用了这个方法。

如果你有一个这样的嵌套状态:

   this.state = {
          formInputs:{
            friendName:{
              value:'',
              isValid:false,
              errorMsg:''
            },
            friendEmail:{
              value:'',
              isValid:false,
              errorMsg:''
            }
}

你可以声明handleChange函数来复制当前状态并重新赋值

handleChange(el) {
    let inputName = el.target.name;
    let inputValue = el.target.value;

    let statusCopy = Object.assign({}, this.state);
    statusCopy.formInputs[inputName].value = inputValue;

    this.setState(statusCopy);
  }

这里是带有事件侦听器的HTML

<input type="text" onChange={this.handleChange} " name="friendName" />

There is another option and this works if there are multiple items in the list of objects: copy the object using this.state.Obj to a variable (say temp), use filter() method to traverse through the object and grab the particular element you want to change into one object(name it updateObj) and the remaining list of object into another object(name this as restObj). Now edit the contents of object you want to update creating a new item (say newItem). Then call this.setUpdate() and use spread operators to assing new list of objects to the parent object.

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


var temp=[...this.state.someProperty]
var restObj = temp.filter((item) => item.flag !== true);
var updateObj = temp.filter((item) => item.flag === true);

var newItem = {
  flag: false
};
this.setState({ someProperty: [...restObj, newItem] });

把它写在一行里

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

我看到每个人都给出了基于类的组件状态更新解决方案,这是预期的,因为他要求,但我试图给钩子相同的解决方案。

const [state, setState] = useState({
    state1: false,
    state2: 'lorem ipsum'
})

现在,如果你想改变嵌套对象键state1,那么你可以做以下任何一项:

过程1

let oldState = state;
oldState.state1 = true
setState({...oldState);

流程2

setState(prevState => ({
    ...prevState,
    state1: true
}))

我最喜欢过程。

用于多个输入控件和动态嵌套名称

<input type="text" name="title" placeholder="add title" onChange={this.handleInputChange} />
<input type="checkbox" name="chkusein" onChange={this.handleInputChange} />
<textarea name="body" id="" cols="30" rows="10" placeholder="add blog content" onChange={this.handleInputChange}></textarea>

代码非常易读

处理程序

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