How can I insert into React's state array with setState?

后端 未结 5 2011
礼貌的吻别
礼貌的吻别 2021-02-01 18:42

I\'m looking to modify and array in react and insert elements on specific index. This is how my state looks like:

this.state = {arr: [\'\', \'\', \'\', \'\' ]}
<         


        
5条回答
  •  借酒劲吻你
    2021-02-01 19:35

    Two Ways to do:

    1. Using concat :

    NOTE: It is not allowed to use the array push method, because it mutates the array. It doesn’t leave the array intact but changes it. Instead, there should be a new array created which is used to update the state.

    Array concat method creates a new array, leaving the old array intact, but also returning a new array from it.

    this.state = {
          value: '',
          list: ['a', 'b', 'c'],
        };
    
    this.setState(state => {
    const list = state.list.concat(state.value);
    return {
            list,
            value: '',
          };
    });
    
    1. Using ...spread operator :
    this.state = {
          value: '',
          list: ['a', 'b', 'c'],
        };
    
    this.setState(state => {
    const list = [...state.list, state.value]; <--insert in end -->``
    const list = [state.value, ...state.list]; <--Or insert in start -->
    return {
            list,
            value: '',
          };
    });
    

    Reference : https://www.robinwieruch.de/react-state-array-add-update-remove/

提交回复
热议问题