我试图实现经过身份验证的路由,但是发现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>
将被忽略
在这种情况下,实现此目标的正确方法是什么?
它出现在react-router
(v4)文档中,提示类似
<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
还是带有其他挂钩?