我在过去的几个测试项目中玩过state和setState,但现在我正在开发一个新项目,当我做this.state = new ProductDto("some product name");
时,我得到错误“Cannot convert type ProductDto to type {(): any;(): any}
”。如何在状态中使用setState并在使用TypeScript的ReactJs中使用setState
,当我还做this.setState(product);
我得到一个错误:
Supplied parameter do not match any signature of call target because no overload accepts one parameters.Candidates are:
K<any>() => (void)
K<any>() => (void)
我的代码看起来是这样的。
class ProductDto {
constructor(name?: string) {
this.name = name;
}
name: string;
}
class Product extends React.Component<any, ProductDto> {
constructor() {
super();
this.state = new ProductDto("some product name");
}
handleChangeProduct(product: ProductDto) {
this.setState(product);
}
...
}
我使用typescript: "^2.2.1", @types/react: "^15.0.13" and react": "^15.4.2"
和的setState的定义是这样的index.d.ts文件
setState<K extends keyof S>(f: (prevState: S, props: P) => Pick<S, K>, callback?:() => any): void;
setState<K extends keyof S>(state: Pick<S, K>, callback?:() => any): void;
。
任何帮助如何让这些工作将不胜感激。谢谢。
使用类作为状态非典型,可能有问题,React如何处理状态......而只是使用接口和对象文字。您可以使用'{product:ProductDto}'作为您的状态。 – Aaron
为'this.state'提供一个普通对象。 –
@Aaron我也尝试过使用接口和对象字面值,但它没有帮助。 –