【发布时间】:2021-02-13 04:59:09
【问题描述】:
您好,我不知道如何解释,但这是我想要做的:
LoginDispatch.ts
const useLoginDispatch = () => {
const dispatch = useDispatch()
const setLoginScreen = (screen: LoginScreen) => {
dispatch(loginActions.setLoginScreen(screen))
}
const setRegisterError = (message: string) => {
dispatch(loginActions.setRegisterError(message))
}
// This is a lot of code to write just to dispatch() each action, I would need
// to do this hundreds of times
// Can I automate this process?
// Notice how the exports below have the same name as the loginActions exports
return { setLoginScreen , setRegisterError}
}
我所做的只是将dispatch() 应用于从loginActions 导出的每个函数。要更改我的应用程序的登录屏幕,我可以输入:
LoginComponent.tsx
const loginDispatch = useLoginDispatch()
loginDispatch.setLoginScreen(LoginScreen.Register)
而不是:
LoginComponent.tsx
const dispatch = useDispatch()
dispatch(loginActions.setRegisterError(message))
现在我可以像现在一样继续手动向 LoginDispatch.ts 添加功能,但我的应用程序中有数百个操作。有没有办法可以自动将dispatch 映射到 LoginActions.ts 中的所有导出,并使用它们的原始函数名称导出它们。
如果您想查看,这是我的 Actions.ts 文件。 (每个导出的结构都是一样的,当然除了参数和返回类型)
Actions.ts
export const setLoginScreen = (screen: LoginScreen): LoginActionTypes => ({
type: LoginActions.SET_LOGIN_SCREEN,
payload: screen
})
export const setRegisterError = (message: string): LoginActionTypes => ({
type: LoginActions.SET_REGISTER_ERROR,
payload: message
})
注意:我将 Actions.ts 保持不变,因为我还有其他函数(在 sagas 中),例如 put(),它们也调用这些函数。
【问题讨论】:
标签: typescript react-redux react-hooks