3 回答

TA貢獻1848條經驗 獲得超2個贊
您將要使用該Redirect組件。有幾種不同的方法可以解決此問題。我喜歡的一個是,有一個PrivateRoute組件,該組件接受一個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 path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />
如果您仍然感到困惑,我寫了這篇文章可能會有所幫助 -React Router v4的受保護路由和身份驗證

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