[英]TypeScript Error - Type 'Ticket[] | undefined' is not an array type
How do I append an item to an array of objects to a state (React) while using TS?如何在使用 TS 时将项目 append 到 state (React) 的对象数组?
This is my code:这是我的代码:
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]
})
}
I keep getting this error:我不断收到此错误:
Type 'Ticket[] |
输入'票[] | undefined' is not an array type.
undefined' 不是数组类型。
I tried:我试过了:
let addData:Ticket[] = this.fetchNewData()
too and the error I get:也是我得到的错误:
Type 'Promise<Ticket[]>' is missing the following properties from type 'Ticket[]': length, pop, push, concat, and 28 more.
类型 'Promise<Ticket[]>' 缺少类型 'Ticket[]' 的以下属性:length、pop、push、concat 和另外 28 个。 Type 'Ticket[] |
输入'票[] | undefined' is not an array type.
undefined' 不是数组类型。
I tried writing it in all kind of variations with no luck.我试着用各种变体写它,但没有运气。
Both pointing error in this line :此行中的两个指向错误:
> 144 | tickets: [...this.state.tickets, addData]
| ^
There are few problems in your code, you can fix those:您的代码中存在一些问题,您可以解决这些问题:
export type AppState = {
tickets: Ticket[] // remove the ?
// ...
}
constructor(props) {
super(props)
this.state = {
tickets: [],
// ...
}
}
addData
is array of Ticket
, you need to make handleLoadMore
function async
to use await
on this.fetchNewData
to get the data returned by it:addData
是Ticket
的数组,您需要使handleLoadMore
function 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),
})
}
You should destructure adddata
as well.您还应该解构
adddata
。
tickets: [...this.state.tickets, ...addData]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.