【问题标题】:Any way to make "const {user, userId} = this.state" work if user references username and userId references id [duplicate]如果用户引用用户名和 userId 引用 id [重复],任何使“const {user,userId} = this.state”工作的方法
【发布时间】:2020-07-01 22:23:54
【问题描述】:

例如

 state = { 
      "username": "abc",
      "id": "1",
 } 


 const {username, id} = this.state

上面的代码可以工作并获取值

有没有办法让它在下面也可以工作

const {user, userId} = this.state

即获取与用户名、id 相同的值但名称不同。有什么方法可以告诉 javascript user 表示用户名,userId 表示 id?

【问题讨论】:

  • 我不知道你指的是不是别名,如果是这样,你可以这样const {username:user, id: userId} = this.state;然后你可以在你的代码中使用useruserId
  • 参见 codeburst 的 THIS 指南。它解释了你在寻找什么:)

标签: javascript reactjs


【解决方案1】:

如果你只想使用不同的名字,你可以这样做:

const {username: user, id: userId} = this.state

【讨论】:

    【解决方案2】:

    是的,你可以这样做:

    const {username: user, id: userId} = this.state
    

    这里有很棒的文档https://javascript.info/destructuring-assignment

    【讨论】:

    • 哎呀,我想我是第三个给你同样答案的人。对不起,冗余
    【解决方案3】:

    分配给新的变量名:

    const o = {p: 42, q: true};
    const {p: foo, q: bar} = o;
     
    console.log(foo); // 42 
    console.log(bar); // true
    

    更多信息:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2021-06-18
      • 1970-01-01
      • 2018-05-12
      相关资源
      最近更新 更多