2017-03-02 194 views
1

我在过去的几个测试项目中玩过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;

任何帮助如何让这些工作将不胜感激。谢谢。

+2

使用类作为状态非典型,可能有问题,React如何处理状态......而只是使用接口和对象文字。您可以使用'{product:ProductDto}'作为您的状态。 – Aaron

+0

为'this.state'提供一个普通对象。 –

+0

@Aaron我也尝试过使用接口和对象字面值,但它没有帮助。 –

回答

2

反应状态必须是一个对象。 setState接受一个对象或返回一个对象作为第一个参数的函数。也就是说,状态对象可以包含类(这是函数)。

在你情况下,你可以设置状态如下

this.state = { product: new ProductDto("some product name") }; 

,然后更新它

this.setState({ product }); 

你可以阅读更多关于反应状态在这里:https://facebook.github.io/react/docs/state-and-lifecycle.html