【问题标题】:What is the proper way to access an object inside state using a key?使用键访问状态内部对象的正确方法是什么?
【发布时间】:2022-06-15 16:00:00
【问题描述】:

我正在使用 React Typescript 构建一个应用程序,并且我的状态定义如下:

  const [products, setProducts] = useState({
    fruits: [],
    veggies: [],
    herbs: [],
  });

当我想从HTML select 添加产品时,比如说水果,我将在onChange 函数中调用以下代码:

addProduct("fruits", value);

函数addProduct 如下所示。我使用productType 作为访问products 中特定产品类型的密钥:

const addProduct = (productType: string, value: string) => {
  setProducts((products) => ({
    ...products,
    [productType]: [...products.productType, value],
  }));
}

但是,我收到了这个错误(截图附在链接上): TS2339: Property 'productType' does not exist on type '{ fruits: never[]; veggies: never[]; herbs: never[]; }'. 其中...products.productType 突出显示。

我尝试使用美元符号标识符、模板文字访问...products.productType,但无济于事。如何访问...products.productType?是否有正确的语法可供使用,或者是否有解决此问题的 hacky 解决方案?

【问题讨论】:

  • 初始设置状态时需要告诉TS[]是什么类型。

标签: javascript reactjs typescript


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-31
  • 1970-01-01
  • 2020-12-05
相关资源
最近更新 更多