javascriptreact-nativeecmascript-6exporeact-native-fetch-blob

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


The use of this seems always confusing to me. As in the below source code. Can anyone explain what does the statement const {tz, msg} = this.state; mean in the below code?

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;


Solution

  • const {tz, msg} = this.state; is equivalent to

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

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