【问题标题】:react-router: functions are not valid react child反应路由器:功能无效反应子
【发布时间】:2019-01-17 23:30:06
【问题描述】:

我注意到很多问题都被问到了关于作为 react child 无效的函数,但从我所看到的情况来看,没有一个适合我的情况。

我使用 react-router 和错误(函数作为 React 子级无效。如果您返回组件而不是从渲染中返回,则可能会发生这种情况。或者您可能打算调用此函数而不是返回它。) 当我尝试使用 Es6 类语法创建我的 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 的类语法改成这样的函数,

    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>   
);

完美运行。我不知道为什么会这样

【问题讨论】:

  • 你如何渲染App
  • 在像这样的另一个文件中 ReactDOM.render(App, document.getElementById('root'));

标签: javascript reactjs function react-router es6-class


【解决方案1】:

根据 Garret Motzner 的评论,我从这里切换了 Dom 渲染功能

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

ReactDOM.render(&lt;App /&gt;, document.getElementById('root'));

它现在可以工作了

【讨论】:

    猜你喜欢
    • 2019-10-02
    • 1970-01-01
    • 2019-01-07
    • 2020-09-30
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    相关资源
    最近更新 更多