TypeScript 错误 - 类型 'Ticket[] | undefined' 不是数组类型

TypeScript Error - Type 'Ticket[] | undefined' is not an array type

如何在使用 TS 时将项目附加到对象数组到状态 (React)?

这是我的代码:

export type AppState = {
    tickets?: Ticket[],
}

export type Ticket = {
    id: string,
    title: string;
}

export type ApiC = {
    getTickets: (order:string, page:number) => Promise<Ticket[]>;
}

export class App extends React.PureComponent<{}, AppState> {

    state: AppState = {
    }


   fetchNewData = async () => {
        return await api.getTickets(this.state.currentOrder, this.state.page)
   }

    handleLoadMore = () => {

       let addData:Promise<Ticket[]> = this.fetchNewData()

        if (addData) 
            this.setState({
                tickets: [...this.state.tickets, addData]
            })
    }

我不断收到此错误:

Type 'Ticket[] | undefined' is not an array type.

我试过了:

let addData:Ticket[] = this.fetchNewData()

也是,我得到的错误是:

Type 'Promise<Ticket[]>' is missing the following properties from type 'Ticket[]': length, pop, push, concat, and 28 more. Type 'Ticket[] | undefined' is not an array type.

我尝试用各种变体编写它,但没有成功。

这一行都指向错误:

  > 144 |               tickets: [...this.state.tickets, addData]
        |                            ^

你也应该解构 adddata

tickets: [...this.state.tickets, ...addData]

您的代码中有一些问题,您可以解决这些问题:

  1. 从状态中移除可选项并用空数组初始化它
export type AppState = {
  tickets: Ticket[] // remove the ?
  // ...
}

constructor(props) {
  super(props)
  this.state = {
    tickets: [],
    // ...
  }
}
  1. 假设 addDataTicket 的数组,您需要使 handleLoadMore 函数 async 以在 this.fetchNewData 上使用 await 来获得它返回的数据:
handleLoadMore = async () => {
  let addData = await this.fetchNewData()

  if (addData)
    this.setState({
      tickets: [...this.state.tickets, ...addData],
    })
    // Or
    this.setState({
      tickets: this.state.tickets.concat(addData),
    })
}