我还在学js。制作阿波罗图形教程:https://www.apollographql.com/docs/tutorial/introduction/
我不太明白这部分:findOrCreateUser({ email: emailArg } = {})
完整代码如下:

   /**
   * User can be called with an argument that includes email, but it doesn't
   * have to be. If the user is already on the context, it will use that user
   * instead
   */
  async findOrCreateUser({ email: emailArg } = {}) {
    const email =
      this.context && this.context.user ? this.context.user.email : emailArg;
    if (!email || !isEmail.validate(email)) return null;

    const users = await this.store.users.findOrCreate({ where: { email } });
    return users && users[0] ? users[0] : null;
  }

  async bookTrips({ launchIds }) {
    const userId = this.context.user.id;
    if (!userId) return;

    let results = [];

    // for each launch id, try to book the trip and add it to the results array
    // if successful
    for (const launchId of launchIds) {
      const res = await this.bookTrip({ launchId });
      if (res) results.push(res);
    }

    return results;
  }

请教育我,否则链接到解释就可以了。谢谢。

最佳答案

findOrCreateUser({ email: emailArg } = {})

是几个原则的结合
1)对象分解
const { prop } = obj;

相当于:
const prop = obj.prop;

2)函数参数解构
除了函数的参数
function fun({ prop }) {
  console.log(prop);
}

相当于
function fun(obj) {
  console.log(obj.prop);
}

3)解构时重命名变量
function fun({ prop: newPropName }) {
  console.log(newPropName);
}

相当于
function fun(obj) {
  const newPropName = obj.prop;
  console.log(newPropName);
}

4)默认功能参数
function fun(arg = 5) {
  console.log(arg);
}

fun(10); // prints 10
fun(); // prints 5 since no value was passed to fun

结论:
findOrCreateUser({ email: emailArg } = {}) {
 // [...]
}

相当于
findOrCreateUser(args) {
  const emailArg = args ? args.email : {};
  // [...]
}

换句话说,它将传递给方法的对象的email属性重命名为emailArg并使其直接可用。如果未向函数传递任何内容,它还会将参数初始化为空对象。这是为了避免在没有传递任何内容的情况下触发aCannot read email of undefined
如果您需要更多上下文,请参阅以下文档:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assigning_to_new_variable_names

关于javascript - 有人可以向我解释一下:“create({email:emailArg} = {}){}”吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57107654/

10-12 17:36