typescript - 将函数应用于对象的所有导出并使用相同的名称导出
问题描述
嗨,我不确定如何解释这一点,但这是我正在尝试做的事情:
登录调度.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添加函数,但我的应用程序中有数百个操作。有没有一种方法可以自动映射dispatch
到LoginActions.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(),它们也调用这些函数。
解决方案
您可以尝试以下方法:
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]
);
};
推荐阅读
- mule - 如何检查有效载荷内的空数组?
- python - namedtuple 和 NamedTuple 有什么区别?
- java - 如何在 Gradle 插件中检查/读取 Java 文件
- python - Python HTTPSConnection 异常
- c# - 按钮循环 ASP.NET
- javascript - 在向 li 添加新课程之前删除课程
- vim - vim 删除所有包含 X 或更多单词的行
- java - Project Reactor 中反应流的内存转换
- python - 为什么我在 CUDA 中收到 cuMemcpyDtoH_v2 的未定义符号错误
- jquery - Ajax 未捕获类型错误:无法重新定义属性: