我试图通过 addTask 方法在我的任务数组中添加一个任务对象,这个方法获取以前的状态并添加新任务,它适用于 JSX
但当我使用 typescript 。我得到的错误是
Type 'ITask[] | undefined' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. TS2569
import React, { Fragment } from 'react';
interface ITask {
name: string;
done: boolean;
}
interface IProps {
}
interface IState {
newTask?: string;
tasks?: Array<ITask>;
}
class App extends React.Component<IProps, IState>{
constructor(props: any) {
super(props);
this.state = {
newTask: '',
tasks: []
}
}
addTask(name:string) {
this.setState(prevState => ({
tasks: [...prevState.tasks, {name, done: false}]
}));
}
render() {
return (
<Fragment>
</Fragment>
);
}
}
最佳答案
您可能必须将新对象显式键入为 ITask
,以告诉 TypeScript 编译器您正在将类型为 ITask
的对象推送到 tasks
状态。
此外,tasks
是可选的。解决此问题的一种方法是在传播时设置默认值(空数组 []
)。
addTask(name:string) {
const newTask: ITask = {name, done: false}
this.setState((prevState) => ({
tasks: [...(prevState.tasks ?? []), newTask]
}));
}
鉴于 tasks
(甚至 newTask
)实际上在构造函数中被分配了一个值,实际上没有必要在您的 IState 中将其标记为可选
界面。
interface IState {
newTask: string;
tasks: Array<ITask>;
}
这将使您无需在设置状态时检查 tasks
是否为 undefined
。
关于reactjs - 推送状态数组 React with TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61200631/