React-redux:遍历道具和组件填充
问题描述:
我有一个名为Dashboard的连接React组件,它应该填充Plot组件。应通过映射一组JSON对象来创建这些组件,通过API调用将其检索并置于状态,然后通过函数mapStateToProps()映射到props。React-redux:遍历道具和组件填充
API调用正在工作。 mapStateToProps也在工作。然而,我试图在道具中绘制JSON对象数组,并且从每个道具创建一个Plot组件失败,并出现以下错误:无法读取未定义的属性'map'
我怀疑发生了什么事情,因为我已经将相关的映射代码放入render()生命周期钩子中,代码正试图在API调用返回之前运行。所以,当它试图去做时,它没有什么财产。是这样吗?如果是这样,我该如何解决?
我的剧情成分:
import React from 'react';
const Plot = ({ props }) => {
return (
<div className="media">
<div className="media-left">
<a href="#">
<img className="media-object" src="http://placehold.it/200/550" alt="Placehold" />
</a>
</div>
<div className="media-body">
<h4 className="media-heading">{props.name}</h4>
<ul>
<li><strong>Grower: </strong> {props.grower}</li>
<li><strong>Region: </strong> {props.region}</li>
<li><strong>Current State: </strong> {props.currentState}</li>
<li><strong>Next State: </strong> {props.nextState}</li>
<li><strong>Days To Next State: </strong> {props.daysToNext}</li>
<br />
<span class="pull-right">
<i id="like1" class="glyphicon glyphicon-thumbs-up"></i> <div id="like1-bs3"></div>
<i id="dislike1" class="glyphicon glyphicon-thumbs-down"></i> <div id="dislike1-bs3"></div>
</span>
</ul>
</div>
</div>
);
};
export default Plot;
我的控制面板组件:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
import Plot from './plot';
class Dashboard extends Component {
componentWillMount() {
this.props.fetchMessage();
this.props.fetchPlots();
}
render() {
const plots = this.props.plots;
return (
<div>
<span>{this.props.message}</span>
<div className='container'>
{plots.map((plot) => <Plot name={plot.name} grower={plot.grower} region={plot.region} currentState={plot.currentState} nextState={plot.nextState} daysToNext={plot.daysToNext}/>)}
</div>
</div>
);
}
}
function mapStateToProps(state)
{
return {
message: state.auth.message,
plots: state.auth.plots
}
}
export default connect(mapStateToProps, actions)(Dashboard);
答
{plots && plots.map((plot) => <Plot name={plot.name} grower={plot.grower} region={plot.region} currentState={plot.currentState} nextState={plot.nextState} daysToNext={plot.daysToNext}/>)}
您只需将地图功能之前,空校验,使其只执行,如果有数据
很棒。不幸的是,我的Plot组件有什么问题 - 我得到了这个:'Uncaught(在promise中)TypeError:无法读取未定义的属性'name'。这可能是什么?通常,当您使用作为默认导出的大括号导入类时,会发生此错误,但这里不是这种情况。有任何想法吗? –
检查您的数据一次。这个错误是由于{plot.name} 检查名称是否存在于图中 –
确实如此。 –