【问题标题】:Unable to setState array of objects - Typescript无法设置对象数组 - 打字稿
【发布时间】: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


【解决方案1】:

那是因为您的函数可能返回未定义。 您可以将 useState 挂钩更新为

const [quantity, setQuantity] = React.useState<any[] | undefined>([
    {
      id: '1',
      q: 100,
    },
    {
      id: '2',
      q: 50,
    },
    {
      id: '3',
      q: 50,
    },
  ]);

【讨论】:

  • 当我这样更新它时,我得到另一个错误。 'any[] 类型的参数 | undefined' 不可分配给“any[]”类型的参数。类型 'undefined' 不能分配给类型 'any[]'。我使用数量数组的每个地方都会弹出此错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 2022-06-28
  • 2018-08-31
  • 2023-03-07
相关资源
最近更新 更多