*抱歉,我之前曾发布过一个类似的问题,但由于它是结构更好的问题而将其删除。
你好!我想将PixaBay API中的largeImageURL
定位到PhotoResults容器中的GridTile
中。我已经将Redux配置到了应用程序中。提交this.props.photos
后控制台searchText
日志时,我收到一个长度为20的数组。我知道0:
中的0: 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);
答案 0 :(得分:1)
尝试一下。最初,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>
);
}