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

Javascript 语句const{tz,msg}=this.state是什么意思;在下面的代码中是什么意思?,javascript,react-native,ecmascript-6,expo,react-native-fetch-blob,Javascript,React Native,Ecmascript 6,Expo,React Native Fetch Blob,这个词的用法总是让我感到困惑。如下面的源代码所示。 谁能解释一下语句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是什么意思;在下面的代码中是什么意思

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;


这意味着您的状态有两个键值对,如
tz
msg


所以,每当像这样键入时,您直接从中获取值,然后从中打印值,如
tz
msg

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

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

它被称为。基本上,它将减少代码行数。如果您可以研究其他方面,这将是一件好事。

这在Javascript中称为
对象解构。您可以将其用于对象和数组

喜欢

你可以在这里进一步阅读

所以你的情况是

const {tz, msg} = this.state
类似于将其作为

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

这就是所谓的对象分解。这是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);
解构


你可以在这里获得更多关于解构的信息:

尽管我还有另一个疑问,但这似乎非常令人信服。在前面的一节课中,他们用另一种方式定义了tz和msg导出类时间形式扩展React.Component{constructor(props){super(props);this.fetchCurrentTime=this.fetchCurrentTime.bind(this);this.handleFormSubmit=this.handleFormSubmit.bind(this);this.handleChange=this.handleChange.bind(this);const{tz,msg}=this.props;this.state={tz,msg};}“``是一样的。ES6解构赋值。这很有帮助。谢谢。哦,好的。但是,为什么有人要重新给已经定义的标题、宽度和高度赋值呢?我们不是在重新赋值。这些是对象的属性,我们是使用解构直接访问它的。假设你有一个HTTP响应对象,你想检索
名称
。您只需使用
const{name}=response
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);