我试图实现经过身份验证的路由,但是发现React Router 4现在阻止了它的工作:
<Route exact path="/" component={Index} /> <Route path="/auth" component={UnauthenticatedWrapper}> <Route path="/auth/login" component={LoginBotBot} /> </Route> <Route path="/domains" component={AuthenticatedWrapper}> <Route exact path="/domains" component={DomainsIndex} /> </Route>
错误是:
警告:您不应使用<Route component>和<Route children>在同一路线上;<Route children>将被忽略
<Route component>
<Route children>
在这种情况下,实现此目标的正确方法是什么?
它出现在react-router(v4)文档中,提示类似
react-router
<Router> <div> <AuthButton/> <ul> <li><Link to="/public">Public Page</Link></li> <li><Link to="/protected">Protected Page</Link></li> </ul> <Route path="/public" component={Public}/> <Route path="/login" component={Login}/> <PrivateRoute path="/protected" component={Protected}/> </div> </Router>
但是在将一堆路线组合在一起时是否有可能实现这一目标?
更新
好吧,经过一番研究,我想到了这个:
import React, {PropTypes} from "react" import {Route} from "react-router-dom" export default class AuthenticatedRoute extends React.Component { render() { if (!this.props.isLoggedIn) { this.props.redirectToLogin() return null } return <Route {...this.props} /> } } AuthenticatedRoute.propTypes = { isLoggedIn: PropTypes.bool.isRequired, component: PropTypes.element, redirectToLogin: PropTypes.func.isRequired }
发出错误的动作是正确的render()感觉。似乎确实不正确,componentDidMount还是带有其他挂钩?
render()
componentDidMount
您将要使用该Redirect组件。有几种不同的方法可以解决此问题。我喜欢的一个是,有一个PrivateRoute组件,该组件接受一个authed道具,然后根据该道具进行渲染。
Redirect
authed
function PrivateRoute ({component: Component, authed, ...rest}) { return ( <Route {...rest} render={(props) => authed === true ? <Component {...props} /> : <Redirect to={{pathname: '/login', state: {from: props.location}}} />} /> ) }
现在你Route的可以看起来像这样
Route
<Route path='/' exact component={Home} /> <Route path='/login' component={Login} /> <Route path='/register' component={Register} /> <PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />