Zen*_* Qu 14 reactjs typescript2.0
我正在使用Microsoft TypeScript-React-Starter并在以下期间遇到此编译错误npm start:
./src/index.tsx
(16,5): error TS2605: JSX element type 'App' is not a constructor function for JSX elements.
Types of property 'setState' are incompatible.
Type '{ <K extends never>(f: (prevState: null, props: {}) => Pick<null, K>, callback?: (() => any) | un...' is not assignable to type '{ <K extends never>(f: (prevState: {}, props: any) => Pick<{}, K>, callback?: (() => any) | undef...'.
Types of parameters 'f' and 'f' are incompatible.
Type '(prevState: {}, props: any) => Pick<{}, any>' is not assignable to type '(prevState: null, props: {}) => Pick<null, any>'.
Types of parameters 'prevState' and 'prevState' are incompatible.
Type 'null' is not assignable to type '{}'.
Run Code Online (Sandbox Code Playgroud)
所以看起来我的setState功能有不正确的签名,但我不知道如何解决它.这是我的代码:
class App extends React.Component<{}, null> {
render() {
return (
<div className="App">
...
</div>
);
}
}
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root') as HTMLElement
);
Run Code Online (Sandbox Code Playgroud)
我在用:
node v6.11.0
npm v5.1.0
typescript v2.4.1
react v15.6.1
redux v3.7.1
react-redux v5.0.5
react-scripts-ts v2.3.2
Run Code Online (Sandbox Code Playgroud)
更新:
我发现删除泛型类型可以<{}, null>清除错误.但我仍然想知道为什么我会收到错误.
Man*_*nth 18
TLDR; 国家不能为空.为它声明一个接口或声明它{}
答案在于@ types/react
查看定义,state和props都不是null.
当你声明App为class App extends React.Component<{}, null> {,你基本上说,"状态是null类型".
现在,类型setState取决于您为state指定的类型,并且它与setState api的较小的已知版本冲突.prevState声明为{}(默认情况下,因为没有指定state的接口),这与null不兼容,导致您看到的错误日志.
| 归档时间: |
|
| 查看次数: |
13019 次 |
| 最近记录: |