Push method in React Hooks (useState)?

后端 未结 8 682
無奈伤痛
無奈伤痛 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:32

    I tried the above methods for pushing an object into an array of objects in useState but had the following error when using TypeScript:

    Type 'TxBacklog[] | undefined' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)

    The setup for the tsconfig.json was apparently right:

    {
       "compilerOptions": {
       "target": "es6",
       "lib": [
          "dom",
          "dom.iterable",
          "esnext",
          "es6",
    ],
    

    This workaround solved the problem (my sample code):

    Interface:

       interface TxBacklog {
          status: string,
          txHash: string,
       }
    

    State variable:

        const [txBacklog, setTxBacklog] = React.useState();
    

    Push new object into array:

        // Define new object to be added
        const newTx = {
           txHash: '0x368eb7269eb88ba86..',
           status: 'pending'
        };
        // Push new object into array
        (txBacklog) 
           ? setTxBacklog(prevState => [ ...prevState!, newTx ])
           : setTxBacklog([newTx]);
    

提交回复
热议问题