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

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

提交回复
热议问题