2017-01-08 34 views
2

我正在使用React和Redux編寫Web應用程序。我有一個Redux動作,它使用XMLHttpRequest來從REST API向我的Reducer填充數據(以數組格式)。我在componentDidMount中調用action,因爲這就是React文檔所說的最好。當我嘗試在我的渲染函數中訪問它們時,我得到一個「數組[0]在控制檯中是未定義的消息。」但有趣的是,如果我定義一個使用array.map()返回JSX的函數,那麼它可以正常工作。它只是不允許我單獨訪問它們。有誰知道這是爲什麼?從API調用訪問React中的單個數組元素

代碼:

import React from 'react' 
import {connect} from 'react-redux' 
import {bindActionCreators} from 'redux' 
import {Row, Col, Grid} from 'react-bootstrap' 
import {fetchData} from '../actions' 

class DataContainer extends React.Component { 

    listData(array){ 
    return array.map((element) => { 
     return(
     <Col lg = {3} md = {4} sm = {6} key = {element.id}> 
      <h3>{element.name}</h3> 
      <p>{element.description}</p> 
     </Col> 
    ); 
    }); 
    } 

    componentDidMount(){ 
    this.props.getData() //call API 
    } 

    render() { 
     return(
     <Grid> 
      <Row componentClass = "section" id = "non-profits"> 
      {listData(props.data)} //this works 
      {props.data[0].name} //this doesn't work 
      </Row> 
     </Grid> 
    ); 

    } 
} 

function mapStateToProps(state){ 
    return{ //maps reducer state to props for use in component 
    data: state.data //state.data stores the data from the REST API 
    }; 
} 

function mapDispatchToProps(dispatch){ 
    return bindActionCreators({getdata: fetchdata}, dispatch)//fetchData is the redux action that 
                  //calls the REST API 

} 

export default connect(mapStateToProps, mapDispatchToProps)(DataContainer); 
+0

你最初的'data'狀態是什麼樣的? – azium

+0

組件第一次安裝時,數據將不存在。 Javascript是異步的,你的組件會在你進行ajax調用之前掛載(它是「DID MOUNT」回調)。你正在試圖在它被設置之前查找一個道具。你需要在你的渲染fn –

+0

中處理這種情況,但是如果數據不存在,爲什麼array.map會起作用?這似乎是如果數據不存在,那麼當我將它傳遞給列表函數時它不應該是不確定的嗎?並且初始數據狀態只是一個空數組 – user2757964

回答

2

試試這個:

render() { 
      return(
      <Grid> 
       <Row componentClass = "section" id = "non-profits"> 
        {(props && props.data && props.data.length > 0)} ? {props.data[0].name} : <span>None</span> //This should work 
       </Row> 
      </Grid> 
      ); 
     } 

我沒有測試此代碼。但這應該工作。

+0

謝謝,那是行得通的。我曾經嘗試過測試道具和props.data,但是測試props.data.length> 0原來是使它工作的條件。我仍然對array.map()好奇,但如果任何人有答案 – user2757964

+0

當應用程序初始化數據數組是空的。因此,它仍然是「loopable」,所以數組映射將起作用。 'props.data [0]'訪問數組中的第一個元素,但如果數組在應用程序加載時爲空,則會因爲訪問不存在的東西而出錯。此外,只要數組已定義,您仍然可以使用for語句遍歷空數組。 – Luke101