这个渲染方法做了什么:const {images, selectedImage} = this.state;?

What does this render method do: const {images, selectedImage} = this.state;?

我正在做一个关于 react/redux 的简单教程,我不明白为什么我们必须在 render() 方法中做

const {images, selectedImage} = this.state;

我知道我们需要将之前定义的变量分配给构造函数,因此它成为我们组件状态的一部分,而不仅仅是在我们的组件中浮动的变量,但我不明白为什么我们不能稍后直接在渲染方法中访问它们?我也不明白为什么它们被定义为常量?我也不明白为什么他们被分配到状态以及为什么他们有括号?非常感谢您的帮助

import React, {Component} from 'react'

const flickrImages = [
  "https://farm2.staticflickr.com/1553/25266806624_fdd55cecbc.jpg",
  "https://farm2.staticflickr.com/1581/25283151224_50f8da511e.jpg",
  "https://farm2.staticflickr.com/1653/25265109363_f204ea7b54.jpg",
  "https://farm2.staticflickr.com/1571/25911417225_a74c8041b0.jpg",
  "https://farm2.staticflickr.com/1450/25888412766_44745cbca3.jpg"
];

export default class Gallery extends Component {
  constructor(props) {
    super(props);
    this.state = {
      images: flickrImages,
      selectedImage: flickrImages[0]
    }
  }

  handleThumbClick(selectedImage) {
    this.setState({
      selectedImage
    })
  }

  render() {
    const {images, selectedImage} = this.state; // why do we have to do this? And why does this need to be a constant?
    return (
      <div className="image-gallery">
        <div className="gallery-image">
          <div>
            <img src={selectedImage} />
          </div>
        </div>
        <div className="image-scroller">
          {images.map((image, index) => (
            <div key={index} onClick={this.handleThumbClick.bind(this,image)}>
              <img src={image}/>
            </div>
          ))}
        </div>
      </div>
    )
  }
}

PS:如果你能为这个问题建议一个更好的标题,请告诉我,我不确定如何称呼它,我相信有一个更好的名字在这里完成

叫做object destructuring

它将this.state.images分配给局部常量images,将this.state.selectedImage分配给局部常量selectedImage

we call it Object destructuring:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

// (1) Your example:
const {images, selectedImage} = this.state;

// (2) same as this
const images = this.state.images;
const selectedImage this.state.selectedImage;



//Another Example
Basic assignment
const user = {
    id: 42,
    isVerified: true
};

const {id, isVerified} = user;

console.log(id); // 42
console.log(isVerified); // true