我正在尝试将路由器上下文传递给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>
);
答案 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) => {...})