【发布时间】:2018-04-16 16:29:14
【问题描述】:
我尝试使用 redux 和 react-router-dom 在 typescript 中构建一个 react 应用程序。当我将 redux 添加到我的应用程序时,我遇到了打字问题。因此,我创建了以下最小示例,只有一页 test-page:
App.jsx
import * as React from 'react';
import { Route, Redirect } from 'react-router-dom'
import Test from './containers/test-page'
import './App.css';
class App extends React.Component {
render() {
return (
<div className="ui container" id="main">
<Route exact path="/" render={() => <Redirect to="/test" />}/>
<Route exact path="/test" component={Test} />
</div>
);
}
}
export default App;
测试页面的容器如下所示。它会在调用 connect 时产生输入错误。
containers/test-page/index.tsx
import { Dispatch } from 'redux'
import { connect } from 'react-redux'
import TestPage from './test-page'
function mapDispatchToProps(dispatch: Dispatch<any>) {
return dispatch({ type: 'ALERT_USER' });
}
function mapStateToProps(state: any) {
return { label: 'my test label' }
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(TestPage)
容器使用以下反应组件,在生产中应该为路由器渲染一个页面。它产生两个错误,见下文。
containers/test-page/test-page.tsx
import * as React from 'react';
export namespace Test {
export interface Props {
alert: () => void;
label: string;
}
export interface State {
}
}
export default class TestPage extends React.Component {
constructor(props?: Test.Props, state?: Test.State, context?: any) {
super(props, context);
}
sendAlert = () => {
this.props.alert()
}
render() {
return (
<div>
<h1>Test</h1>
<button onClick={this.sendAlert}>{this.props.label}</button>
</div>
);
}
}
错误信息:
proxyConsole.js:54 ./src/containers/test-page/test-page.tsx
(20,18): error TS2339: Property 'alert' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'.
proxyConsole.js:54 ./src/containers/test-page/test-page.tsx
(27,54): error TS2339: Property 'label' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'.
proxyConsole.js:54 ./src/containers/test-page/index.tsx
(16,3): error TS2345: Argument of type 'typeof TestPage' is not assignable to parameter of type 'ComponentType<{ label: string; } & { type: string; }>'.
Type 'typeof TestPage' is not assignable to type 'StatelessComponent<{ label: string; } & { type: string; }>'.
Type 'typeof TestPage' provides no match for the signature '(props: { label: string; } & { type: string; } & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.
我尝试遵循不同的指南并查找示例实现,但无法解决这些问题。我不明白打字稿编译器的错误信息:
- 为什么我定义的属性在
this.props上不存在? - 究竟什么不能在连接中分配?
【问题讨论】:
标签: javascript reactjs typescript redux react-redux