function App() {
const view = useSelector(viewsSelector);
const isAuth = () => {
if(view === ''){
return false;
}
if(view === 'welcome'){
return true;
}
}
console.log(isAuth());
const PrivateRoute = ({component: Component, ...rest}) => {
return(
<Route {...rest} render={(props) => (
isAuth()
? <Component {...props}/>
: <Redirect to='/Login'/>
)}/>
)
}
return(
<Router>
<Header/>
<Switch>
<Route exact path='/Login' component={Login}/>
<Route path='/About' component={About}/>
<Route path='/Contact' component={Contact}/>
<Route path='/Help' component={Help}/>
<PrivateRoute path='/Welcome' component={Welcome}/>
</Switch>
</Router>
)
}
我正在使用私有或受保护的路由。
isAuth()
在 false
时有效,除了 Login
但是isAuth()
从false
变为true
,它不会将路由重定向到path='./Welcome
如何在 isAuth()
更改时重定向?
答案 0 :(得分:0)
您需要将 isAuth
结果传递给 PrivateRoute
,否则它不知道 isAuth
何时发生变化。
function App() {
const view = useSelector(viewsSelector);
const isAuth = () => {
if (view === "") {
return false;
}
if (view === "welcome") {
return true;
}
};
console.log(isAuth());
const PrivateRoute = ({ component: Component, canView, ...rest }) => {
return (
<Route
{...rest}
render={(props) =>
canView ? <Component {...props} /> : <Redirect to="/Login" />
}
/>
);
};
return (
<Router>
<Header />
<Switch>
<Route exact path="/Login" component={Login} />
<Route path="/About" component={About} />
<Route path="/Contact" component={Contact} />
<Route path="/Help" component={Help} />
<PrivateRoute path="/Welcome" component={Welcome} canView={isAuth()} />
</Switch>
</Router>
);
}