React Typescript 如何将新数组添加到对象数组 useState

React Typescript How to add a new array to an array of objects useState

我在!我在我的 React 项目中使用 typescript。现在我想创建一个对象数组的 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

        );
        .
        .
        .
    }
}

试试这个!

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

这是 setState 的文档

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