【问题标题】:React: Nothing was returned from render. This usually means a return statement is missing反应:渲染没有返回任何内容。这通常意味着缺少返回语句
【发布时间】:2021-09-10 05:03:05
【问题描述】:

如何解决这个错误?

错误:CountryList(...):渲染没有返回任何内容。这通常意味着缺少 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;

【问题讨论】:

  • 由于错误是从CountryList 内部抛出的,您必须添加相同的代码。

标签: javascript html reactjs frontend web-deployment


【解决方案1】:

您可能不会从 CountryList 组件返回任何内容。 你应该检查你的退货声明。如果你为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(....)
     )

     
 }

【讨论】:

  • return 不应该在 render() 里面吗?
猜你喜欢
  • 2021-06-24
  • 2021-07-25
  • 1970-01-01
  • 2020-09-06
  • 2021-03-14
  • 2018-12-08
  • 2021-05-13
相关资源
最近更新 更多