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

后端 未结 5 2006
礼貌的吻别
礼貌的吻别 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:19

    use spread operator https://codeburst.io/javascript-es6-the-spread-syntax-f5c35525f754

    let newChild = "newChild"
    
    this.setState({
        children: [
            ...this.state.children,
            newChild
        ]
    })
    
    0 讨论(0)
  • 2021-02-01 19:24

    Clone the current state using slice(). By doing this, the original state remains unaffected till setState(). After cloning, do your operations over the cloned array and set it in the state. The previous answer will mutate the state. Read about this here

    let a = this.state.arr.slice(); //creates the clone of the state
    a[index] = "random element";
    this.setState({arr: a});
    
    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2021-02-01 19:40

    UPDATE

    Just use Object.assign() as suggested here to make a copy of your state.

    Thus, you can do it as follows :

    let new_state = Object.assign({}, this.state); 
    let a = new_state.arr;
    a[index] = "random element";
    this.setState({arr: a});
    

    Hope it helps.

    0 讨论(0)
  • 2021-02-01 19:43

    Immer is a common dependency to help with this kind of thing. In this example, you would do something like

    import {useImmer} from "use-immer"
    
    export default function MyComponent(props) {
       const [state, setState] = useImmer({arr: ['', '', '', '' ]})
    
       // .... some time later
    
       setState(draft => {
           draft.arr[index] = newValue
       })
    }
    

    And Immer will take care of making sure that your state is updated immutably and correctly.

    0 讨论(0)
提交回复
热议问题