我試圖實施認證的路線卻發現陣營路由器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