Reactjs 如何在react redux中正确键入映射到道具的动作创建者
在我们的项目中,所有动作创建者的定义如下:Reactjs 如何在react redux中正确键入映射到道具的动作创建者,reactjs,typescript,redux,react-redux,Reactjs,Typescript,Redux,React Redux,在我们的项目中,所有动作创建者的定义如下: export const actionCreatorFunctionName(arg1, arg2...) { return (dispatch: Dispatch, getStore: () => StoreState) => { // ... function logic ... dispatch(actionFunctionName(args...)); } } import * as
export const actionCreatorFunctionName(arg1, arg2...) {
return (dispatch: Dispatch, getStore: () => StoreState) => {
// ... function logic ...
dispatch(actionFunctionName(args...));
}
}
import * as ActionCreators from "./actionCreators";
connect(mapStateToProps, { actions: ActionCreators })(SomeComponent);
interface Props {
actions: typeof ActionCreators;
}
一些操作创建者发出HTTP请求,在请求得到解决之前不调用dispatch
使用connect
hoc将这些动作创建者映射到道具,如下所示:
export const actionCreatorFunctionName(arg1, arg2...) {
return (dispatch: Dispatch, getStore: () => StoreState) => {
// ... function logic ...
dispatch(actionFunctionName(args...));
}
}
import * as ActionCreators from "./actionCreators";
connect(mapStateToProps, { actions: ActionCreators })(SomeComponent);
interface Props {
actions: typeof ActionCreators;
}
问题是,在使用此设置时,似乎不可能为组件正确配置props接口。我们已经尝试过这样配置道具:
export const actionCreatorFunctionName(arg1, arg2...) {
return (dispatch: Dispatch, getStore: () => StoreState) => {
// ... function logic ...
dispatch(actionFunctionName(args...));
}
}
import * as ActionCreators from "./actionCreators";
connect(mapStateToProps, { actions: ActionCreators })(SomeComponent);
interface Props {
actions: typeof ActionCreators;
}
但这不起作用,因为
actions
道具实际上与ActionCreators
不同,因为connect
hoc将ActionCreators从返回函数的函数更改为普通函数。如果我理解正确,从存储
向组件发送状态
时遇到问题?
如果是这种情况,我们假设您的存储中有一个名为items的对象的数据,将下面的代码放在组件中connect语句的上方(这使组件可以使用items
数据)
我认为除了定义动作之外,您还需要定义一个
动作
类型,您可以在道具中导出和使用它
export type Actions = {
action1: (arg1: string) => void,
action2: (arg1: string, arg2: number) => void
}
export function action1(arg1: string) {
// ...
}
然后使用道具中的操作
界面
type Props = {
actions: Actions
}
问题是如何将分派映射到props,而不是state我认为除了定义实际操作之外,您还需要定义一个包含每个函数的所有方法签名的操作类型,然后在props中导入并使用它