【问题标题】:Typescript, Redux - Set type for DISPATCHTypescript, Redux - 为 DISPATCH 设置类型
【发布时间】:2020-03-16 04:03:42
【问题描述】:

这一定是我处理过的最烦人的事情了。

究竟如何在 react/redux/typescript 中为调度设置类型?代码如下:sn-p:

class MyComponent extends Component<StateFromProps> { // Do I need a <..., DispatchFromProps> here?
  ...
  const mapStateToProps = (state: StateFromProps) => {
    return {
      counter: state.counter
    }
  }

  const mapDispatchToProps = (dispatch) => {
    return {
      onAddCounter: (amount: number) => dispatch({ type: 'ADD_COUNTER', value: amount })
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)

上面几行,我为状态和调度定义了接口。这似乎适用于状态,但不适用于调度。

interface StateFromProps {
  counter: number
}

interface DispatchFromProps {
  onAddCounter: () => void  // I can't get this part right. I am getting errors about call signatures etc.
}

我想分派如下操作:

this.props.onAddCounter(5)  // ERROR: Property 'onAddCounter' does not exist on type 'Readonly<StateFromProps>'...

【问题讨论】:

  • 是的,您传递给class MyComponent extends Component&lt; 的道具应该是它们的总和。您可以选择不将它们区分为 StateFromPropsDispatchFromProps,只需在 Props 中定义它们并在您的组件中使用它就可以了
  • 如何在 props 中定义它们?你介意发布一个这样的小例子吗?
  • 您可以快速查看我的演示库herehere,并随时在本地分叉并亲自尝试。
  • 是的,如果该 HOC 没有进一步的问题,官方方法似乎更好

标签: reactjs typescript redux


【解决方案1】:

所以这似乎几乎可以工作:

问题Component&lt;T&gt; 似乎只接受第一个参数。

class MyComponent extends Component<StateFromProps, DispatchFromProps> {
  ...
}

StateFromProps 是传递给Component第一个 类型参数时,我可以访问State

DispatchFromProps第二个 参数时,所有Dispatch 代码都会中断。

如果我更改顺序并将DispatchFromProps 放在第一位,Dispatch 代码可以工作,但所有State 代码都会中断。

如何正确使用Component的多种类型?

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 2018-09-28
    • 1970-01-01
    • 2018-08-31
    • 2021-12-07
    • 2021-10-22
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    相关资源
    最近更新 更多