React:渲染中没有 returned。这通常意味着缺少 return 语句

React: Nothing was returned from render. This usually means a return statement is missing

如何修复抛出的错误?

Error: CountryList(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './Containers/App';
import reportWebVitals from './reportWebVitals';
import 'tachyons';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

App.js

import React, { Component } from 'react';
import './App.css';
import NavBar from '../Components/NavBar';
import SideBar from '../Components/SideBar';
import CountryList from '../Components/CountryList';

class App extends Component {

  constructor() {
    super();
    this.state = {
      nations: []
    }
  }

  componentDidMount() {
    fetch('https://restcountries.eu/rest/v2/all%27)
      .then(response => response.json())
      .then(x => this.setState({ nations: x }));
  }

  render() {
    const { nations } = this.state;
    return (
      <div>
        <NavBar />
        <SideBar>
          <CountryList nations={nations} />
        </SideBar>
      </div>
    );
  }

}

export default App;

您可能 return CountryList 组件中没有任何内容。 您应该检查您的 return 声明。如果你为 nations prop 设置任何条件,也许你做错了什么。 我猜你喜欢这个。

CountryList extends React.Component{
  if(nations) {
     return nations.map(nation => ...)
  }
}

但你应该这样做

 CountryList extends React.Component{
      if(nations) {
         return nations.map(nation => ...)
      } else {
         return null;
      }
    }

或更好的方法:

 CountryList extends React.Component{
     // ...do some stuff before return
     return (
         this.props.nations?.length > 0 && this.props.nations.map(....)
     )

     
 }