typescript 带有打字稿的 mapDispatchToProps 很困难

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43809640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:31:06  来源:igfitidea点击:

mapDispatchToProps with typescript is being difficult

reactjstypescriptredux

提问by Chaim Friedman

Trying to build a simple react crud app with typescript and redux and ran in to the following issue. I have a function that has the specified signature that it will take a person object as an argument as seen here.

尝试使用 typescript 和 redux 构建一个简单的 react crud 应用程序,但遇到了以下问题。我有一个函数,它具有指定的签名,它将一个人对象作为参数,如下所示。

export default function savePerson(person: Person) {
    return async (dispatch: any) => {
        let newPerson = await axios.post('/api/people/addPeron', person);
        dispatch(addPersonSuccess(person));
    }
}

Now when I am trying to connnect my component to redux I am having trouble with the mapDispatchToProps. Here is my code.

现在,当我尝试将我的组件连接到 redux 时,我遇到了mapDispatchToProps. 这是我的代码。

function mapDispatchToProps(dispatch: any) {
  const actions = {
    savePerson: () => dispatch(savePerson())
  }
  return actions;
}

The issue is that the savePerson function requires a person to be passed to it, however I do not have access to my state in the mapDispatchToProps, and since the function is missing arguments my code wont compile. Any ideas?

问题是 savePerson 函数需要将一个人传递给它,但是我无法访问 中的状态mapDispatchToProps,并且由于该函数缺少参数,因此我的代码无法编译。有任何想法吗?

EDIT WITH SOLUTION:

使用解决方案进行编辑:

Here is the code with the one change needed to make this code work.

这是使此代码工作所需的一项更改的代码。

function mapDispatchToProps(dispatch: any) {
  const actions = {
    savePerson: (person: Person) => dispatch(savePerson(person))
  }
  return actions;
}

I just had to pass the person object to my anonymous function that is calling dispatch.

我只需要将 person 对象传递给我的匿名函数,该函数调用dispatch.

采纳答案by Yozi

import { AnyAction } from "redux";
import { ThunkDispatch } from "redux-thunk";
import { savePerson } from "../myActions";

// IExtraDispatchArguments usually is empty
import { IExtraDispatchArguments, IStoreState } from "../myGlobalTypes"

interface IMyComponentProps {
    savePerson: (person: Person) => Promise<void>;
}
class MyComponent extends React.Component<IMyComponentProps, void>{
    someMethod(person: Person) {
        this.actions.savePerson(person);
    }
}

const WrappedComponent = connect(
   (state: IStoreState, ownProps: {}) => ({
       // here you can map state
   }),
   (dispatch: (dispatch: ThunkDispatch<IStoreState, IExtraDispatchArguments, AnyAction>)) => ({
      // savePerson: (person: Person) => dispatch(savePerson(person))
      actions: {
         savePerson: (person: Person) => dispatch(savePerson(person))
      }
   }
);