0

*抱歉,因为我之前发布了一个类似的问题,但由于这是一个结构更好的问题,所以将其删除。

你好!我想largeImageURL从 PixaBay API 定位到GridTile在我的 PhotoResults 容器中呈现。我已将 Redux 配置到应用程序中。this.props.photos当我在提交 a 后控制台日志时searchText,我收到一个长度为 20 的数组。我知道0:in0: Array(20)表示第一个索引位置,但我不知道这如何帮助我定位largeImageURL. 我如何定位largeImageURL到在GridTile? 非常感谢!

在此处输入图像描述

减速器

import * as actionTypes from '../actions/actions_index';

const photos = (state = [], action) => {
  switch(action.type) {
    case actionTypes.FETCH_PHOTOS:
      console.log('Action received', action);
      return [ action.payload.data.hits ];
    default:
      return state;
  }
}

export default photos;

照片结果容器

import React, { Component } from 'react';
import {GridList, GridTile } from 'material-ui/GridList';
import { connect } from 'react-redux';

class PhotoResults extends Component {
  render() {
    let photoList;
    if (this.props.photos) {
      photoList = (
        <GridList cols={3}>
          {this.props.photos.map(photo => (
            <GridTile title={photo.tags} key={photo.id}>
            <img src={photo.largeImageURL} alt="" />
            </GridTile>
          ))}
        </GridList>
      )
    } else {
      photoList = null;
    }
    console.log(this.props.photos);
    return (
      <div>
        {photoList}
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return { photos: state.photos };
}

export default connect(mapStateToProps, null)(PhotoResults);
4

1 回答 1

0

尝试这个。最初 this.props.photos 将是未定义的,因此您需要在执行 .map 之前进行条件检查

  return(){
      return(
           <div>
              <GridList cols={3}>
                  {this.props.photos && Array.isArray(this.props.photos[0]) && this.props.photos[0].length > 0 && this.props.photos[0].map(photo => (
                     <GridTile title={photo.tags} key={photo.id}>
                         <img src={photo.largeImageURL} alt="" />
                    </GridTile>
                   ))}
    </GridList>
          </div>
      )
  }

这也可以,但我不建议渲染中的其他内容

    render() {
       let photoList;
       if (this.props.photos && Array.isArray(this.props.photos[0]) && this.props.photos[0].length > 0)
           photoList = (
               <GridList cols={3}>
                    {this.props.photos[0].map(photo => (
                       <GridTile title={photo.tags} key={photo.id}>
                         <img src={photo.largeImageURL} alt="" />
                       </GridTile>
                    ))}
               </GridList>
              )
             } else {
             photoList = null;
            }
            console.log(this.props.photos);
           return (
           <div>
              {photoList}
           </div>
          );
        }
于 2018-10-10T02:37:43.953 回答