【问题标题】:How to correctly type action creators mapped to props in react-redux如何在 react-redux 中正确键入映射到道具的动作创建者
【发布时间】:2023-03-20 11:45:01
【问题描述】:

在我们的项目中,所有动作创建者的定义如下:

export const actionCreatorFunctionName(arg1, arg2...) {
    return (dispatch: Dispatch, getStore: () => StoreState) => {
        // ... function logic ...
        dispatch(actionFunctionName(args...));
    }
}

一些动作创建者发出 HTTP 请求,在请求解决之前不调用 dispatch

这些动作创建者使用connect hoc 映射到道具,如下所示:

import * as ActionCreators from "./actionCreators";

connect(mapStateToProps, { actions: ActionCreators })(SomeComponent);

问题是使用此设置时似乎无法正确配置组件的 props 接口。我们尝试过像这样配置 Props:

interface Props {
    actions: typeof ActionCreators;
}

但这不起作用,因为actions prop 与ActionCreators 的类型并不相同,因为connect hoc 将actionCreators 从返回函数的函数更改为普通函数。

【问题讨论】:

  • 我认为除了定义实际动作之外,您还需要定义一个包含每个函数的所有方法签名的动作类型,然后在您的道具中导入并使用它

标签: reactjs typescript redux react-redux


【解决方案1】:

我认为除了定义动作之外,您还需要定义一个Actions 类型,您可以将其导出并在您的道具中使用。

export type Actions = {
  action1: (arg1: string) => void,
  action2: (arg1: string, arg2: number) => void
}

export function action1(arg1: string) {
  // ...
}

然后在你的 props 中使用Actions 接口

type Props = {
  actions: Actions
}

【讨论】:

    【解决方案2】:

    如果我理解正确,您在将statestore 发送到组件时遇到问题? 如果是这种情况,我们假设您的商店中有一个名为 items 的对象的数据,将以下代码放在组件中的 connect 语句上方(这使得 items 数据可用于您的组件);

    const mapStateToProps = (state) => {
      items: state.items
    }
    

    【讨论】:

    • 问题是关于将调度映射到道具,而不是状态
    猜你喜欢
    • 2017-11-07
    • 2017-01-30
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2016-12-16
    • 2016-12-03
    相关资源
    最近更新 更多