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);
처음 '데이터'상태는 어떻게 생겼습니까? – azium
처음으로 구성 요소를 탑재하면 데이터가 존재하지 않습니다. Javascript가 비동기 적이기 때문에 구성 요소가 마운트됩니다 (AIDA 콜을하기도 전에 "DID MOUNT"콜백 임). 소품을보기 전에 소품을 찾으려고합니다. 렌더링 fn –
에서 해당 케이스를 처리해야합니다. 그러나 데이터가 존재하지 않으면 왜 array.map이 작동합니까? 데이터가 존재하지 않는다면 목록 함수에 전달할 때 정의되지 않아야하는 것처럼 보입니까? 그리고 초기 데이터 상태는 단지 빈 배열입니다 – user2757964