我正在使用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);
你最初的'data'狀態是什麼樣的? – azium
組件第一次安裝時,數據將不存在。 Javascript是異步的,你的組件會在你進行ajax調用之前掛載(它是「DID MOUNT」回調)。你正在試圖在它被設置之前查找一個道具。你需要在你的渲染fn –
中處理這種情況,但是如果數據不存在,爲什麼array.map會起作用?這似乎是如果數據不存在,那麼當我將它傳遞給列表函數時它不應該是不確定的嗎?並且初始數據狀態只是一個空數組 – user2757964