【发布时间】:2021-10-29 13:12:45
【问题描述】:
我是 TypeScript 的新手。我正在尝试更新对象数组的状态。
对象数组:
const [quantity, setQuantity] = React.useState<any[]>([
{
id: '1',
q: 100,
},
{
id: '2',
q: 50,
},
{
id: '3',
q: 50,
},
]);
我正在使用我用来更新数组的函数来更新这个数组。 该函数正常工作并返回正确答案。 (结果应该是新的状态)
import update from 'immutability-helper';
export const updateProductQuantity = (
products: any[],
id: any,
operation: 'increase' | 'decrease',
minValue: number
) => {
const index = products.findIndex((product) => product.id === id);
let updatedQuantity, newQuantities;
if (operation === 'increase') {
updatedQuantity = products[index].q + 1;
} else {
updatedQuantity = products[index].q - 1;
let newValue = updatedQuantity - 1;
if (minValue && newValue < minValue) return;
}
const updatedProduct = { id: id, q: updatedQuantity };
newQuantities = update(products, {
$splice: [[index, 1, updatedProduct]],
});
return newQuantities;
};
我在这里更新状态。
const newQuantities = updateProductQuantity(quantity, id, 'increase', 1);
setQuantity(newQuantities);
附:参数传递正确
我在这一行遇到错误:
setQuantity(newQuantities);
这是错误:
Argument of type 'any[] | undefined' is not assignable to parameter of type 'SetStateAction<any[]>'.
Type 'undefined' is not assignable to type 'SetStateAction<any[]>'. TS2345
【问题讨论】:
-
newQuantities是什么?将其添加到问题中(需要 console.log(newQuantities))
标签: reactjs typescript setstate