语句 const {tz, msg} = this.state; 是什么意思?在下面的代码中是什么意思?

What does the statement const {tz, msg} = this.state; mean in the below code?

这个的使用似乎总是让我感到困惑。如下面的源代码。 谁能解释一下语句 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;

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

所以每当这样输入时,您都会直接从中获取值,然后您是否从那里打印值,例如 tzmsg

const {tz, msg} = this.state; 等同于

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

叫做ES6 Destructuring Assignment. Basically it will reduce lines of code. It will be good if you can look into other ES6 features

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

喜欢。

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

这就是所谓的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