react-router: 函数无效反应 child

react-router: functions are not valid react child

我注意到有人问了很多关于函数无效的问题 child 但 none 符合我所看到的情况。

我使用 react-router 和错误 (Functions are not valid as a React child。如果你 return 一个组件而不是来自渲染,这可能会发生. 或者也许你打算调用这个函数而不是 return 它 。) 当我尝试使用 Es6 class 语法创建我的 App 组件时发生。 这是我的代码:

    import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
//all other imports are here too
    class App extends Component {
  render () {
    return (
      <Router>
        <div className="App">
          <Header />

          <Switch>
            <Route path ='/blog/' component={Blog} />
            <Route path ='/about/' component={About} />
            <Route path ='/register/' component={Register} />
            <Route component={Carousel} />
          </Switch>

              <Route path='/' exact component={Main} />
              <Route path='/foreign/' component={Foreign} />
              <Route path='/local/' component={Local} />
              <Route path='/snacks/' component={Snacks} />



        </div>

      </Router>   
    );
  }
}

如果我将 Es6 class 语法更改为这样的函数,

    const App = (
    <Router>
      <div className="App">
        <Header />

        <Switch>
          <Route path ='/blog/' component={Blog} />
          <Route path ='/about/' component={About} />
          <Route path ='/register/' component={Register} />
          <Route component={Carousel} />
        </Switch>

        <Route path='/' exact component={Main} />
        <Route path='/foreign/' component={Foreign} />
        <Route path='/local/' component={Local} />
        <Route path='/snacks/' component={Snacks} />



      </div>

    </Router>   
);

效果很好。我不知道为什么会这样

根据 Garret Motzner 的评论,我将 Dom 渲染功能从这个

切换为

ReactDOM.render(App, document.getElementById('root'));

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

现在可以使用了