我试图实施认证的路线却发现阵营路由器4现在可以避免这种情况的工作:如何在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>
但ISIT可能实现这一点的同时分组一堆路线在一起吗?
UPDATE
好了,经过一番研究,我想出了这个:
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
}
ISIT正确派遣在render()
的行动感到不对劲。它似乎不正确componentDidMount
或其他钩子?
最好的,如果不使用服务器端渲染上componetWillMount做。 – mfahadi
@mfahadi,感谢您的意见。我现在还没有使用SSR,但如果我想在未来使用,我是否保持渲染?另外,如果用户在'componentWillMount'中重定向,他们是否会在瞬间看到渲染输出? –
我真的很抱歉,说'componentWillMount()不在SSR上调用,它是不调用的componentDidMount()'。因为在render()之前调用了componentWillMount(),所以用户不会看到任何新组件。所以它是检查的最佳地点。 – mfahadi