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

时间:2016-11-01 10:05:17

标签: reactjs redux react-redux

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

  

const {images,selectedImage} = this.state;

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

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:如果你能为这个问题建议一个更好的标题,请告诉我,我不知道该怎么称呼它,而且我确信这里有更好的名字

1 个答案:

答案 0 :(得分:12)

它被称为object destructuring

它将- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo { _profileImageView.image = image; UIImage *updatedImage = _profileImageView.image; NSData *imageData = UIImageJPEGRepresentation(updatedImage, 100); NSString *strEncoded = [imageData base64EncodedStringWithOptions:0]; [_userDetailsDictionary setObject:strEncoded forKey:@"UpdatedImage"]; [self dismissViewControllerAnimated:YES completion:nil]; } - (IBAction)saveAction:(UIBarButtonItem *)sender { NSLog(@"the values stored in dictionary are %@",_userDetailsDictionary); [[NSUserDefaults standardUserDefaults] setObject:_userDetailsDictionary forKey:@"UpdatedDetails"]; [[NSUserDefaults standardUserDefaults] synchronize]; ConnectionManager * connectionManager = [ConnectionManager sharedConnectionManager]; connectionManager.delegate = self; [connectionManager sendUserUpdatedDetailsToServer:_userDetailsDictionary withToken:[[NSUserDefaults standardUserDefaults] stringForKey:@"token"]]; } 分配给本地常量this.state.imagesimages到本地常量this.state.selectedImage