我已经找到了一个相当不错的基本简化版本,我在the react-redux docs中尝试做的事情.
代码是这样的:
import * as actionCreators from '../actions/index'
import { bindActionCreators } from 'redux'
import React, { Component } from 'react'
import { connect } from 'react-redux'
class TodoApp extends Component {
render() {
return (<div>test!</div>)
}
}
function mapStateToProps(state) {
return { todos: state.todos }
}
function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(actionCreators, dispatch) }
}
export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
我的代码编辑器(带有TSLint扩展名的VS代码)和tsc都将最终(TodoApp)突出显示为错误,这是我得到的消息:
src/components/test.tsx(20,61): error TS2345: Argument of type ‘typeof
TodoApp’ is not assignable to parameter of type ‘ComponentType<{
todos: any; } & { actions: typeof “(filepath)…’. Type ‘typeof
TodoApp’ is not assignable to type ‘StatelessComponent<{ todos: any; }
& { actions: typeof “(filepath)…’.
Type ‘typeof TodoApp’ provides no match for the signature ‘(props: { todos: any; } & { actions: typeof “(filepath)/actions/index”; } & {
children?: ReactNode; }, context?: any): ReactElement | null’.20 export default connect(mapStateToProps,
mapDispatchToProps)(TodoApp)
我的问题是我并不完全理解mapStateToProps和connect正在做什么,但在获得这种理解之前,
我想知道是否有代码更改,我可以在这里修复这个Typescript“错误”.
你可以通过为反应道具添加类型defs来解决这个问题,但是也有很多不安全的隐式使用.如果你为了安全起见完全输入这个应用程序,它看起来像这样….
interface ITodo {
description: string
}
interface ITodosState {
todos: ITodo[]
}
interface ITodoProps {
todos: ITodo[]
}
interface ITodoActionProps {
someAction: () => void
}
class TodoApp extends React.Component<ITodoProps & ITodoActionProps> {
render() {
return (<div>test!</div>)
}
}
function mapStateToProps(state: ITodosState): ITodoProps {
return { todos: state.todos }
}
function mapDispatchToProps(dispatch: Dispatch<ITodosState>): ITodoActionProps {
return bindActionCreators({ someAction: actionCreators.someAction }, dispatch)
}
export default connect<ITodoProps, ITodoActionProps, {}>(mapStateToProps, mapDispatchToProps)(TodoApp)
