打字稿中的 React-Redux 连接问题 [英] React-Redux connect issues in typescript

查看:42
本文介绍了打字稿中的 React-Redux 连接问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个传递给 react-redux 的 connect 函数的组件.组件如下:

I am a trying to make a component which gets passed to react-redux's connect function. The component is as follows:

interface ITestProps {
  id: number
}

class TestComponent extends React.Component<ITestProps, {}> {
  render() {
    return (<div>
      {this.props.name}
    </div>)
  }
}

mapStateToProps(state) {}
mapDispatchToProps(dispatch) {}

let ConnectedComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(TestComponent)

如果我像这样渲染ConnectedComponent,上面的代码似乎可以工作

The above code seems to work find if i render ConnectedComponent like so

<ConnectedComponent></ConnectedComponent>

即没有 id 道具.它不应该抛出错误,因为 ConnectedComponent 只是 TestComponent 的连接形式,TestComponent 应该具有 ITestProps 形式的道具.这是应该的行为方式还是我做错了什么.

i.e without the id prop. Shouldn't it throw an error since the ConnectedComponent is simply the connected form of TestComponent and TestComponent should have props of the form ITestProps. Is this how it is supposed to behave or am I doing something wrong.

推荐答案

我不知道为什么打字不能单独从表现组件推断类型,但是如果在 connect 中输入 ownProps 就可以了 ->

I'm not sure why the typings can't infer the type from the presentational component alone, but it will work if ownProps is typed in connect ->

let ConnectedComponent = connect<{}, {}, ITestProps>(
  mapStateToProps,
  mapDispatchToProps
)(TestComponent)

如果在 mapDispatchToProps 中输入 ownProps 也可以推断 ->

It also can infer it if ownProps is typed in mapDispatchToProps ->

mapStateToProps(state, ownProps: ITestProps) {}

这篇关于打字稿中的 React-Redux 连接问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆