首页 > 解决方案 > 将函数应用于对象的所有导出并使用相同的名称导出

问题描述

嗨,我不确定如何解释这一点,但这是我正在尝试做的事情:

登录调度.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. 要更改我的应用程序的登录屏幕,我可以输入:

登录组件.tsx

const loginDispatch = useLoginDispatch()
loginDispatch.setLoginScreen(LoginScreen.Register)

并不是:

登录组件.tsx

const dispatch = useDispatch()
dispatch(loginActions.setRegisterError(message))

现在我可以像现在一样继续手动向LoginDispatch.ts添加函数,但我的应用程序中有数百个操作。有没有一种方法可以自动映射dispatchLoginActions.ts中的所有导出并使用它们的原始函数名称导出它们。

如果您想查看,这是我的 Actions.ts 文件。(每个导出的结构都是一样的,当然除了参数和返回类型)

动作.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(),它们也调用这些函数。

标签: typescriptreact-reduxreact-hooks

解决方案


您可以尝试以下方法:

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]
  );
};

推荐阅读