3 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
您將要使用該Redirect組件。有幾種不同的方法可以解決此問(wèn)題。我喜歡的一個(gè)是,有一個(gè)PrivateRoute組件,該組件接受一個(gè)authed道具,然后根據(jù)該道具進(jìn)行渲染。
function PrivateRoute ({component: Component, authed, ...rest}) {
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
/>
)
}
現(xiàn)在你Route的可以看起來(lái)像這樣
<Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />
如果您仍然感到困惑,我寫(xiě)了這篇文章可能會(huì)有所幫助 -React Router v4的受保護(hù)路由和身份驗(yàn)證

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
Tnx Tyler McGinnis提供解決方案。我是根據(jù)Tyler McGinnis的想法提出的。
const DecisionRoute = ({ trueComponent, falseComponent, decisionFunc, ...rest }) => {
return (
<Route
{...rest}
render={
decisionFunc()
? trueComponent
: falseComponent
}
/>
)
}
您可以這樣實(shí)現(xiàn)
<DecisionRoute path="/signin" exact={true}
trueComponent={redirectStart}
falseComponent={SignInPage}
decisionFunc={isAuth}
/>
DecisionFunc只是一個(gè)返回true或false的函數(shù)
const redirectStart = props => <Redirect to="/orders" />
添加回答
舉報(bào)