2017-01-08 41 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