【问题标题】:React Typescript How to add a new array to an array of objects useStateReact Typescript如何将新数组添加到对象数组useState
【发布时间】:2021-09-24 13:56:59
【问题描述】:

我在那儿!我在我的 React 项目中使用打字稿。现在我想创建一个对象数组的 useState,但是当我想添加新记录时出现一个重要错误。如何为我的 useState 添加新值?谢谢!

    // interfaces.type.ts
export interface ManagementDocuments {
  id: number;
  idDocument: number;
  name: string;

// shippers.tsx
const [shipperManagementDocumentsSelected, setShipperManagementDocumentsSelected] = useState<ManagementDocuments[]>([]);

const inputChangeHandler = (name, newValue): any => {
    switch (name) {
      case DocumentType.MANAGEMENT:
        // the problem starts here, I don't know how to add a new record to my useState
        setShipperManagementDocumentsSelected(
          ...shipperManagementDocuments,
          newValue

        );
        .
        .
        .
    }
}

【问题讨论】:

  • 什么是newValue,是数组还是对象?如果是数组,是对象数组吗?

标签: reactjs typescript react-typescript


【解决方案1】:

试试这个!

setShipperManagementDocumentsSelected(prev => {
   return [ 
      ...prev,
      newValue
   ]
);

这里是 setState 的文档

https://reactjs.org/docs/hooks-reference.html#usestate

【讨论】:

  • 他的状态是一个数组。
  • 糟糕,更新了! :)
  • 非常感谢!
猜你喜欢
  • 2022-01-16
  • 2021-06-17
  • 2020-08-15
  • 2020-05-10
  • 2016-01-14
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
相关资源
最近更新 更多