加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – Typescript React / Redux:类型’typeof MyClass’

发布时间:2020-12-15 20:15:29 所属栏目:百科 来源:网络整理
导读:我是Redux的新手,也是Novelcript的新手. 我已经找到了一个相当不错的基本简化版本,我在the react-redux docs中尝试做的事情. 代码是这样的: import * as actionCreators from '../actions/index'import { bindActionCreators } from 'redux'import React,{
我是Redux的新手,也是Novelcript的新手.

我已经找到了一个相当不错的基本简化版本,我在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“错误”.

解决方法

您的react组件不需要道具,因此您的连接有错误,因为它推断mapStateToProps和mapDispatchToProps都应返回空对象

你可以通过为反应道具添加类型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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读