javascript - React 路由器错误(失败的 prop 类型 : Invalid prop `children` supplied to `Switch` , 需要一个 ReactNode。)

标签 javascript reactjs router

尝试修改组件,主要思路是,我想创建登录页面,尝试修改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 不调用函数,它只绑定(bind)其上下文。相反,您应该在构造函数中绑定(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>
    )
  }
}

关于javascript - React 路由器错误(失败的 prop 类型 : Invalid prop `children` supplied to `Switch` , 需要一个 ReactNode。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47417690/

相关文章:

javascript - Babel - 无法读取未定义的属性 'TYPED_ARRAY_SUPPORT'

javascript - 使用 .pop 删除特定的数组元素,而不仅仅是最后一个元素 - Redux-form

javascript - 引发 Backbone.js View 事件

javascript - 如何 jQuery 在不同的按钮点击时切换多个图像?

javascript - 'disconnect' 事件(服务器端)上套接字的客户端范围会发生什么情况

reactjs - GraphQL 返回数据但在代码中未定义

javascript - 将 "Route children"和 "cloneElement"转换为 RouterV4

ubuntu - 尝试托管服务器以进行外部访问 - Apache、VirtualBox 和端口转发

angularjs - 模板未在 Angular 路由中加载

javascript - 将html转换为图片(对dom进行快照)