如何推动元素内useState数组反应钩子? 这是react状态下的老方法吗?还是一些新的东西?
例如setState推的例子?
如何推动元素内useState数组反应钩子? 这是react状态下的老方法吗?还是一些新的东西?
例如setState推的例子?
当前回答
如果你想推特定的索引,你可以这样做:
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;
});
};
其他回答
// 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
你可以在自定义状态的末尾追加数据数组:
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]);
我尝试了上面的方法将一个对象推入useState中的对象数组,但在使用TypeScript时出现以下错误:
类型“TxBacklog[] | undefined”必须有一个“符号”。Iterator的方法,返回一个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]);
最推荐的方法是同时使用包装函数和展开运算符。例如,如果你像这样初始化了一个名为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;
});
};