【问题标题】:Is there a way to make this code cleaner?有没有办法让这段代码更干净?
【发布时间】:2019-04-25 19:23:33
【问题描述】:

所以在很多情况下,我必须为具有重复参数的框架和库声明回调函数,有什么方法可以声明它们而无需一次又一次地重复参数...

例子:

(parent, args, ctx, info) => users.find((user) => user.id === parent.author)

(parent, args, ctx, info) => posts.filter((post) => post.author === parent.id) 

(parent, args, ctx, info) => /**an other different function**/ 

。 . .

我不知道它是否合理,但如果我们能做出这样的事情会非常有用:

let args = (parent, args, ctx, info)

(args) => users.find((user) => user.id === parent.author) 

(args) => posts.filter((post) => post.author === parent.id) 

(args) => /**an other different function**/ 

【问题讨论】:

  • 使用对象会起作用吗?例如parent, arg, ctx 可以是一个类或对象,所以你将传入的只是(objWithProps) => objWithProps.users.find((user) => user.id === objWithProps.parent.author)

标签: javascript arguments arrow-functions


【解决方案1】:

在 JavaScript 中,您不必声明不使用的参数,因此您可以这样做:

(parent) => users.find((user) => user.id === parent.author)

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2021-05-23
    • 2021-10-13
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多