<router>在BrowserRouter中可能只有一个子元素

时间:2018-03-01 06:31:44

标签: reactjs react-router react-router-redux react-router-dom

我正在尝试将路由器上下文传递给sidebar组件我收到此错误A <Router>可能只有一个子元素错误。

return (
  <BrowserRouter>
    {({ router }) => (
      <div style={{ display: 'flex', flex: '1' }}>
        {isAuthenticated &&
        <Sidebar
          router={router}
          rooms={currentUserRooms}
          onLogoutClick={this.handleLogout}
        />
        }
        <MatchAuthenticated exactly pattern="/" component={Home} {...authProps} />
        <RedirectAuthenticated pattern="/login" component={Login} {...authProps} />
        <RedirectAuthenticated pattern="/signup" component={Signup} {...authProps} />
        <MatchAuthenticated pattern="/r/:id" component={Room} {...authProps} />
        <Switch component={NotFound} />
      </div>
    )}
  </BrowserRouter>
);

2 个答案:

答案 0 :(得分:0)

正确的方法是使用context,而不是router作为道具。

return (
  <BrowserRouter>
      <div style={{ display: 'flex', flex: '1' }}>
        {isAuthenticated &&
        <Sidebar
          rooms={currentUserRooms}
          onLogoutClick={this.handleLogout}
        />
        }
        <MatchAuthenticated exactly pattern="/" component={Home} {...authProps} />
        <RedirectAuthenticated pattern="/login" component={Login} {...authProps} />
        <RedirectAuthenticated pattern="/signup" component={Signup} {...authProps} />
        <MatchAuthenticated pattern="/r/:id" component={Room} {...authProps} />
        <Switch component={NotFound} />
      </div>
  </BrowserRouter>
);

像这样定义Sidebar

import React from 'react'
import PropTypes from 'prop-types'

const Sidebar = (props, context) => {...}

Sidebar.contextTypes = {
    router: PropTypes.object,
}

Sidebar开始,您可以访问context.router

答案 1 :(得分:0)

您可以使用react-router中的withRouter HOC。

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

const Sidebar = withRouter((props, context) => {...})

参考:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md