2017-01-08 9 views
2

React와 Redux를 사용하여 Webapp를 작성하고 있습니다. XMLHttpRequest를 사용하여 REST API의 데이터 (배열 형식)로 내 감속기를 채우는 Redux 작업이 있습니다. React 문서에서 말하는 것이 최상이기 때문에 componentDidMount에서 액션을 호출합니다. 내 렌더링 기능에서 액세스하려고하면 "배열 [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

처음 '데이터'상태는 어떻게 생겼습니까? – azium

+0

처음으로 구성 요소를 탑재하면 데이터가 존재하지 않습니다. Javascript가 비동기 적이기 때문에 구성 요소가 마운트됩니다 (AIDA 콜을하기도 전에 "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 및 props.data에 대한 테스트를 시도했지만 props.data.length> 0을 테스트하여 작동하게 만든 조건으로 밝혀졌습니다. 난 여전히 궁금해서 array.map() 비록 누군가가 대답을 – user2757964

+0

경우 응용 프로그램을 초기화 할 때 데이터 배열이 비어 있습니다. 따라서 여전히 "loopable"이므로 배열 맵이 작동합니다. 'props.data [0]'는 배열의 첫 번째 요소에 접근하지만, 응용 프로그램로드시 배열이 비어 있으면 존재하지 않는 것을 액세스하기 때문에 오류가 발생합니다. 또한 배열이 정의되어있는 한 for 문을 사용하여 빈 배열을 반복 할 수 있습니다. – Luke101