我正在使用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