您如何使用命名参数来处理函数?

帕提亚猎枪

可以说我有一些这样的代码,

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用Spring Boot仅使用可选查询参数来处理REST API?

如何使用命名参数并防止使用默认构造函数?

转到:调用函数时如何使用命名参数?

Jenkinsfile:如何使用命名参数调用groovy函数

如何用C ++编写几乎相同的具有相同名称的相同函数来处理不同的类参数?

异步python函数来处理PHP

在React事件处理程序中使用参数来处理特定状态

如何使用命令行参数来rar / unrar

如何强制对某些构造函数/函数的调用使用命名参数?

我可以在 flutter 的 **noSuchMethod()** 方法中使用什么参数来处理空快照数据?

在Ruby中使用关键字参数来处理proc

在Pandas中,如何分配一个函数来处理列上的字符串?

如何在Golang中编写函数来处理两种类型的输入数据

如何编写通用函数来处理ReScript中的多种记录类型?

部分使用命名结果参数来设置默认值

使用JPA中的SQL函数来处理时间戳(GMT到给定的UTC)

Golang(初学者):避免使用重复函数来处理字符串或整数

应该在 angular 中使用哪个函数来处理 api post 请求?

Swift构造函数为什么使用命名参数调用?

您如何让Jackson使用Kotlin默认参数来缺失值?

如何在R中使用命名空间处理SVG?

如何处理不使用命名空间的库

您如何在路径中定义使用参数命名文件的函数或脚本?

为了清楚起见,我想在Dart中使用命名参数。我应该如何处理它们?

如何在F#中使用命名参数

如何在C++中使用命名参数

Python:使用一个参数来处理数字和字符串之间的选择吗?

如何在函数中使用命名变量

如何使用命名函数调用attach / detach事件?