必须返回有效的React元素(或null)

问题描述 投票:-1回答:3

迭代列表并在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,数组或其他一些无效对象。

我很确定在渲染函数中返回有一些问题但不确定问题是什么。

编辑:

enter image description here

javascript reactjs redux
3个回答
1
投票

console.log返回undefined,它不是“有效的React元素(或null)”。

用。替换这些电话

console.log('...');
return null;

在所有可能的情况下,你也没有回归。为了安全起见,我还会在最后添加一个return null;


1
投票

您应该使用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>
  )
}

0
投票

在你的代码中,在render方法中,如果this.props.hasErrored结果为true,那么组件将返回undefined并打印控制台消息但反应组件应该返回JSXnull,所以你可以这样做:

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;
        }
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.