Push method in React Hooks (useState)?

后端 未结 8 699
無奈伤痛
無奈伤痛 2020-11-29 15:30

How to push element inside useState array React hook? Is that as an old method in react state? Or something new?

E.g. setState push example ?

8条回答
  •  误落风尘
    2020-11-29 16:23

    To expand a little further, here are some common examples. Starting with:

    const [theArray, setTheArray] = useState(initialArray);
    const [theObject, setTheObject] = useState(initialObject);
    

    Push element at end of array

    setTheArray(prevArray => [...prevArray, newValue])
    

    Push/update element at end of object

    setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));
    

    Push/update element at end of array of objects

    setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);
    

    Push element at end of object of arrays

    let specificArrayInObject = theObject.array.slice();
    specificArrayInObject.push(newValue);
    const newObj = { ...theObject, [event.target.name]: specificArrayInObject };
    theObject(newObj);
    

    Here are some working examples too. https://codesandbox.io/s/reacthooks-push-r991u

提交回复
热议问题