如何推动元素内useState数组反应钩子? 这是react状态下的老方法吗?还是一些新的东西?

例如setState推的例子?


当前回答

当你使用useState时,你可以获得state项的更新方法:

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

然后,当您想要添加一个新元素时,您使用该函数并传入新数组或将创建新数组的函数。通常是后者,因为状态更新是异步的,有时是批处理的:

setTheArray(oldArray => [...oldArray, newElement]);

有时你可以不使用回调表单,如果你只更新处理程序中特定用户事件的数组,如点击(但不像鼠标移动):

setTheArray([...theArray, newElement]);

React确保渲染被刷新的事件是这里列出的“离散事件”。

实例(将回调函数传递给setTheArray):

const {useState, useCallback} = React; function Example() { const [theArray, setTheArray] = useState([]); const addEntryClick = () => { setTheArray(oldArray => [...oldArray, `Entry ${oldArray.length}`]); }; return [ <input type="button" onClick={addEntryClick} value="Add" />, <div>{theArray.map(entry => <div>{entry}</div> )} </div> ]; } ReactDOM.render( <Example />, document.getElementById("root") ); <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>

因为对theArray的唯一更新是在单击事件(“离散”事件之一)中,我可以在addEntry中直接更新:

const {useState, useCallback} = React; function Example() { const [theArray, setTheArray] = useState([]); const addEntryClick = () => { setTheArray([...theArray, `Entry ${theArray.length}`]); }; return [ <input type="button" onClick={addEntryClick} value="Add" />, <div>{theArray.map(entry => <div>{entry}</div> )} </div> ]; } ReactDOM.render( <Example />, document.getElementById("root") ); <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>

其他回答

// Save search term state to React Hooks with spread operator and wrapper function

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])

https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

最推荐的方法是同时使用包装函数和展开运算符。例如,如果你像这样初始化了一个名为name的状态,

控制[names, setNames] = useState(]

你可以像这样推到这个数组,

setNames(names => [...names, newName])

希望这能有所帮助。

如果你想推特定的索引,你可以这样做:

   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;
        });
    };

你可以在自定义状态的末尾追加数据数组:

  const [vehicleData, setVehicleData] = React.useState<any[]>([]);
  setVehicleData(old => [...old, ...newArrayData]);

例如,在下面,你会看到一个axios的例子:

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        {
          url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
          method: 'get',
        }
      );
      setVehicleData(old => [...old, ...result.data.data]);
    };

    fetchData();
  }, [page]);

setTheArray([…theArray newElement]);是最简单的答案,但要注意数组中项目的突变。使用数组项的深度克隆。