2017-09-26 64 views
0

我有一個名爲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); 

回答

2
{plots && plots.map((plot) => <Plot name={plot.name} grower={plot.grower} region={plot.region} currentState={plot.currentState} nextState={plot.nextState} daysToNext={plot.daysToNext}/>)} 

您只需將地圖功能之前,空校驗,使其只執行,如果有數據

+0

很棒。不幸的是,我的Plot組件有什麼問題 - 我得到了這個:'Uncaught(在promise中)TypeError:無法讀取未定義的屬性'name'。這可能是什麼?通常,當您使用作爲默認導出的大括號導入類時,會發生此錯誤,但這裏不是這種情況。有任何想法嗎? –

+0

檢查您的數據一次。這個錯誤是由於{plot.name} 檢查名稱是否存在於圖中 –

+0

確實如此。 –