Push method in React Hooks (useState)?

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

    if you want to push after specific index you can do as below:

       const handleAddAfterIndex = index => {
           setTheArray(oldItems => {
                const copyItems = [...oldItems];
                const finalItems = [];
                for (let i = 0; i < copyItems.length; i += 1) {
                    if (i === index) {
                        finalItems.push(copyItems[i]);
                        finalItems.push(newItem);
                    } else {
                        finalItems.push(copyItems[i]);
                    }
                }
                return finalItems;
            });
        };
    

提交回复
热议问题