将函数应用于对象的所有导出,并使用相同的名称导出



嗨,我不知道如何解释这个,但这是我想做的:

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))

现在我可以继续手动添加函数到logindispatchts就像我已经做了一样,但我的应用程序中有数百个动作。是否有一种方法,我可以自动映射dispatch到所有的出口LoginActions.ts并使用它们原来的函数名导出它们。

这是我的Actions。我的文件,如果你想看的话。(除了参数和返回类型之外,每个导出的结构都是相同的)

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同样,因为我有其他函数(在传奇中),如put(),也调用这些函数。

您可以尝试以下操作:

const useLoginDispatch = () => {
const dispatch = useDispatch();
//memoize the result with useMemo (create only on mount)
return useMemo(
() =>
//make a new object from entries
Object.fromEntries(
//get object entries from loginActions
Object.entries(loginActions)
.filter(
//only if the property is a function
([, value]) => typeof value === 'function'
)
.map(([key, value]) => [
key,
//create a new function that when called will
//  dispatch the result of the original function
//  call
(...args) => dispatch(value(...args)),
])
),
[dispatch]
);
};

最新更新