如何将元素推入useState数组React钩子中? 那是反应状态下的一种旧方法吗?还是新的东西?
答案 0 :(得分:15)
使用useState
时,可以获得状态项的更新方法:
const [theArray, setTheArray] = useState(initialArray);
然后,当您要添加新元素时,可以使用该函数传入新数组:
setTheArray([...theArray, newElement]);
实时示例:
const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntry = useCallback(() => {
setTheArray([...theArray, `Entry ${theArray.length}`]);
});
return [
<input type="button" onClick={addEntry} 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>
答案 1 :(得分:7)
您可以在自定义状态的末尾附加数据数组:
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]);
答案 2 :(得分:3)
在React类组件中以“正常”状态进行操作的方式相同。
示例:
function App() {
const [state, setState] = useState([]);
return (
<div>
<p>You clicked {state.join(" and ")}</p>
//destructuring
<button onClick={() => setState([...state, "again"])}>Click me</button>
//old way
<button onClick={() => setState(state.concat("again"))}>Click me</button>
</div>
);
}
答案 3 :(得分:3)
要进一步扩展, 这是一些常见的例子。开头:
const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);
在数组末尾推送元素
setTheArray(prevArray => [...prevArray, newValue])
在对象末尾推送/更新元素
setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));
在对象数组末尾推送/更新元素
setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);
将元素推到数组对象的末尾
setTheObject(prevState => ({...prevState, currentKey: [...prevState.currentKey, newValue]}));
这里也是一些可行的例子。 https://codesandbox.io/s/reacthooks-push-r991u
答案 4 :(得分:3)
// 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
答案 5 :(得分:1)
最推荐的方法是一起使用包装函数和散布运算符。例如,如果您像这样初始化了一个名为name
的状态,
const [names, setNames] = useState([])
您可以像这样推送到此数组,
setNames(names => [...names, newName])
希望有帮助。
答案 6 :(得分:0)
setTheArray([...theArray, newElement]);
是最简单的答案,但要注意 theArray 中项目的突变。使用数组项目的深克隆。
答案 7 :(得分:0)
我尝试了上述方法将对象推入useState中的对象数组,但使用 TypeScript 时出现以下错误:
输入'TxBacklog [] |未定义”必须具有返回迭代器的“ Symbol.iterator”方法。ts(2488)
tsconfig.json的设置显然是正确的:
{
"compilerOptions": {
"target": "es6",
"lib": [
"dom",
"dom.iterable",
"esnext",
"es6",
],
此解决方法解决了问题(我的示例代码):
接口:
interface TxBacklog {
status: string,
txHash: string,
}
状态变量:
const [txBacklog, setTxBacklog] = React.useState<TxBacklog[]>();
将新对象放入数组:
// Define new object to be added
const newTx = {
txHash: '0x368eb7269eb88ba86..',
status: 'pending'
};
// Push new object into array
(txBacklog)
? setTxBacklog(prevState => [ ...prevState!, newTx ])
: setTxBacklog([newTx]);
答案 8 :(得分:0)
如果您要推送特定索引,可以执行以下操作:
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;
});
};