Have been facing issue while iterating through a list and printing elements in React.
The React Code is:
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);
And I'm getting an error of:
DataList.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
I'm pretty sure there is some issue with returns in the render function of the Not sure what is the issue though.
EDIT:
console.log
returns undefined
, which is not "A valid React element (or null)".
Replace those calls with
console.log('...');
return null;
You are also not return-ing in all possible situations. I'd also add a return null;
at the end just to be safe.
You should wrap your code in render() with a div:
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>
)
}
In your code, inside render
method, if this.props.hasErrored
results in true then the component will return undefined
with printing a console message but react Components should return JSX
or null
, So you can do:
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;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.