3

这个的使用似乎总是让我感到困惑。如以下源代码所示。谁能解释一下语句 const {tz, msg} = this.state; 在下面的代码中是什么意思?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentTime: null, msg: 'now', tz: 'PST'
    }
  }

  getApiUrl() {
    **const {tz, msg} = this.state;**
    const host = 'https://andthetimeis.com';
    return host + '/' + tz + '/' + msg + '.json';
  }

export default App;

4

4 回答 4

1

const {tz, msg} = this.state;相当于

const tz = this.state.tz;
const msg = this.state.msg;

它被称为ES6 解构赋值。基本上它会减少代码行数。如果您可以查看其他ES6 功能,那就太好了。

于 2019-02-13T04:57:46.377 回答
1

那就是所谓的Object destructuring。这是 es6 方法。

解构赋值语法是一种 JavaScript 表达式,它可以将数组中的值或对象中的属性解包到不同的变量中。

旧方法

var obj = {a:1, b:2, c:3};

var a = obj.a;
var b = obj.b;
var c = obj.c;

console.log("value of a is "+ a);
console.log("value of b is "+ b);
console.log("value of c is "+ b);

解构

const obj = {a:1, b:2, c:3};

const { a, b, c } = obj;

console.log("value of a is "+ a);
console.log("value of b is "+ b);
console.log("value of c is "+ b);

您可以在此处获取有关解构的更多信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

于 2019-02-13T05:03:17.907 回答
1

这是Object Destructuring在 Javascript 中调用的。您可以将它与对象和数组一起使用。

喜欢。

For Array

const [a, b] = [10, 20];

For Object

let options = {
  title: "Menu",
  width: 100,
  height: 200
};

let {title, width, height} = options;

您可以在此处进一步阅读https://javascript.info/destructuring-assignment

所以在你的情况下

const {tz, msg} = this.state

类似于访问它

const tz = this.state.tz
const msg = this.state.msg
于 2019-02-13T04:58:22.290 回答
0

这意味着您的状态具有两个键值对,例如tzmsg

因此,每当像这样输入时,您都会直接从中获得价值,那么您是否会像tzand一样从那里打印价值msg

于 2019-02-13T04:53:55.507 回答