我正在使用React和Redux编写Web应用程序。我有一个Redux操作,它使用XMLHttpRequest从REST API中使用数据(以数组格式)填充我的reducer。我在componentDidMount中调用了这个动作,因为React文档说的最好。当我尝试在我的渲染函数中访问它们时,我得到一个"数组[0]在控制台中是未定义的消息。"但有趣的是,如果我定义一个使用array.map()返回JSX的函数,那么它可以正常工作。它只是不允许我单独访问它们。有谁知道为什么会这样?
代码:
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 :(得分: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>
);
}
我没有测试这段代码。但这应该有用。