迭代列表并在React中打印元素时遇到了问题。
反应代码是:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {FetchData} from '../actions/data';
class DataList extends Component{
componentDidMount(){
this.props.fetchData('http://somedomain/api/tweets');
}
renderList(){
return this.props.data.map((i) => (
<li key={i.id} >
{i.body}
</li>
) )
}
render(){
if (this.props.hasErrored){
return console.log('sorry there was an error');
}else if (this.props.isLoading){
return console.log('Loadings...');
}else {
if(this.props.data.length){
return (
<div>{this.renderList()}</div>
);
}
}
}
}
DataList.propTypes = {
fetchData: PropTypes.func.isRequired,
data: PropTypes.array.isRequired,
hasErrored: PropTypes.bool.isRequired,
isLoading: PropTypes.bool.isRequired
};
const mapStateToProps = (state) => {
return {
data: state.data,
hasErrored: state.dataHasErrored,
isLoading: state.dataIsLoading
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: (url) => dispatch(FetchData(url))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(DataList);
我收到的错误是:
DataList.render():必须返回有效的React元素(或null)。您可能已返回undefined,数组或其他一些无效对象。
我很确定在渲染函数中返回有一些问题但不确定问题是什么。
编辑:
console.log
返回undefined
,它不是“有效的React元素(或null)”。
用。替换这些电话
console.log('...');
return null;
在所有可能的情况下,你也没有回归。为了安全起见,我还会在最后添加一个return null;
。
您应该使用div将代码包装在render()中:
render(){
return(
<div>
{if (this.props.hasErrored){
return console.log('sorry there was an error');
}else if (this.props.isLoading){
return console.log('Loadings...');
}else {
if(this.props.data.length){
return (
<div>{this.renderList()}</div>
);
}
}
</div>
)
}
在你的代码中,在render
方法中,如果this.props.hasErrored
结果为true,那么组件将返回undefined
并打印控制台消息但反应组件应该返回JSX
或null
,所以你可以这样做:
render() {
if (this.props.hasErrored){
console.log('sorry there was an error');
return null;
}else if (this.props.isLoading){
console.log('Loadings...');
return null;
}else {
if(this.props.data.length){
return (
<div>{this.renderList()}</div>
);
} else {
return null;
}
}
}