How to update object in React state

后端 未结 5 1353
野的像风
野的像风 2021-02-18 22:30

I have an indexed list of users in the JS object (not array). It\'s part of the React state.

{
    1: { id: 1, name: \"John\" }
    2: { id: 2, name         


        
5条回答
  •  抹茶落季
    2021-02-18 23:09

    Using spreads:

    Adding

    this.setState({
      ...this.state,
      4: { id: 4, name: "Jane" },
    }
    

    Removing id 2

    let prevState = this.state;
    let {"2": id, ...nextState} = prevState;
    this.setState({
      ...nextState,
    }
    

    Changing id 2

    this.setState({
      ...this.state,
      2: {
        ...this.state["2"],
        name: "Peter",
      }
    }
    

提交回复
热议问题