可以说我有一些这样的代码,
const createLogger = ({
dispatch,
frame,
level,
message,
}) => {
dispatch(
actions.debugLog.push({
frame,
level,
message,
}),
)
}
我如何在保留命名参数的同时使用此函数?
并像这样使用
const userLogger = createLogger({
dispatch: useDispatch(),
frame: "userController",
level: "Warning"
// ...potentially other top level keys
})
// user stuff happens
userLogger({ message: "User deleted profile" })()
// later
const adminUserLogger = userLogger({
frame: "adminUserController",
dispatch: adminDispatch
})
用例是在我的应用程序的某些区域将调用此方法,从而减少了重复的代码。
期望增加(上面只是一个例子),但我也想重写某些键。假设我使用一组预设键调用该函数,我想保留这些键,但是这次有了一个new area
。对于更复杂的部分(用于currying的标准用例),此排列的增加。
借鉴slebetman的回答“如何在未知数量的参数上使用函数”的基本结构,并组合对象而不是添加数字:
const createLogFunction = options => {
function curryingLogFunction(newOptions) {
if (newOptions !== undefined) {
// add newOptions into options
options = { ...options, ...newOptions };
return curryingLogFunction;
}
// dispatch isn't part of the object pushed to debugLog, so get a
// version of options that doesn't include it
const { dispatch: _, ...optionsWithoutDispatch } = options;
// for the snippet
console.log(options.dispatch, optionsWithoutDispatch);
//options.dispatch(
// actions.debugLog.push(optionsWithoutDispatch),
//);
}
return curryingLogFunction;
}
const logUserAction = createLogFunction({
dispatch: 'useDispatch()', // string for the snippet, function in your code
frame: "userController",
level: "Warning"
// ...potentially other top level keys
});
// user stuff happens
logUserAction({
message: "User deleted profile"
})();
// later
const logAdminAction = createLogFunction({
frame: "adminUserController",
dispatch: 'adminDispatch'
});
logAdminAction({ message: 'message' })({ currying: 'works' })({ frame: 'override defaults' })()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句