【问题标题】:Apply a function to all exports of an object and export using the same name将函数应用于对象的所有导出并使用相同的名称导出
【发布时间】: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


    【解决方案1】:

    您可以尝试以下方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多