React 路由器错误(道具类型失败:提供给 Switch 的道具 children 无效,需要一个 ReactNode。)

React router error (Failed prop type: Invalid prop `children` supplied to `Switch`, expected a ReactNode.)

尝试修改组件,主要思想是,我想创建登录页面,尝试修改App.js但出现错误

warning.js?6327:36 Warning: Failed prop type: Invalid prop children supplied to Switch, expected a ReactNode.

我的代码是:

class App extends Component {
  constructor(props) {
      super(props)


}

 routeWithSubRoutes(route) {
  return (
    <Route
      key={_.uniqueId()}
      exact={route.exact || false}
      path={route.path}
      render={props => (
        // Pass the sub-routes down to keep nesting
        <route.component {...props} routes={route.routes || null} />
      )}
    />
  );
 } 

 render () {
  return (
    <div className={styles.App}>
    <Helmet {...config.app} />
    <NavBar />
    <Switch>
      {routes.map(route => this.routeWithSubRoutes.bind(this,route))}
    </Switch>
    </div>
  )
 }



}

export default App;

我尝试修改的代码

export default () => {
  // Use it when sub routes are added to any route it'll work

  const login = () => {

  }

  const routeWithSubRoutes = route => (
    <Route
      key={_.uniqueId()}
      exact={route.exact || false}
      path={route.path}
      render={props => (
        // Pass the sub-routes down to keep nesting
        <route.component {...props} routes={route.routes || null} />
      )}
    />
  );

  var isLogin = false;

  if(!isLogin) {
    return (
      <Login />
    )
  }

  if(isLogin) {
    return (
      <div className={styles.App}>
        <Helmet {...config.app} />
        <NavBar />
        <Switch>
          {routes.map(route => routeWithSubRoutes(route))}
        </Switch>
      </div>
    );
  }


};

此代码有效,但我的不行,如何解决?

Function.bind 不调用该函数,它只绑定其上下文。相反,您应该在构造函数中绑定它:

class App extends Component {
  constructor(props) {
    super(props)

    this.routeWithSubRoutes = this.routeWithSubRoutes.bind(this)
  }

  /* ... */

  render () {
    return (
      <div className={styles.App}>
        <Helmet {...config.app} />
        <NavBar />
        <Switch>
          {routes.map(route => this.routeWithSubRoutes(route))}
        </Switch>
      </div>
    )
  }
}