如何将元素推送到 useState 数组 React hook 中?
这是反应状态下的旧方法吗?或者新的东西?
E.g. setState 推送示例 https://stackoverflow.com/questions/41052598/reactjs-array-push-function-not-working-in-setstate ?
当你使用useState https://reactjs.org/docs/hooks-reference.html#usestate,你可以获得状态项的更新方法:
const [theArray, setTheArray] = useState(initialArray);
然后,当您想要添加新元素时,您可以使用该函数并传入新数组或将创建新数组的函数。通常是后者,因为状态更新是异步的,有时是批量的:
setTheArray(oldArray => [...oldArray, newElement]);
有时,如果您不使用回调表单,您也可以逃脱only更新处理程序中某些特定用户事件的数组,例如click
(但不喜欢mousemove
):
setTheArray([...theArray, newElement]);
React 确保刷新渲染的事件是列出的“离散事件”here https://github.com/facebook/react/blob/master/packages/react-dom/src/events/plugins/SimpleEventPlugin.js.
现场示例(将回调传递到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
那里有一个click
事件(“离散”事件之一),我可以直接更新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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)