[英]React: private route not navigating
用戶登錄后,我正在使用私有路由導航到某個路由。但是,我遇到了一個問題。 我不知道為什么,但我的路由器沒有轉換到所需的路由。 這是我的代碼:
路由.js
...
...
<PrivateRoute
authenticated={localStorage.getItem("isAuthenticated")}
path="/dashboard"
component={DashBoard}
exact
></PrivateRoute>
PrivateRoute.js
const PrivateRoute = ({ component: Component, authenticated, ...rest }) => (
<Route
{...rest}
render={props =>
authenticated ? (
<Component {...rest} {...props} />
) : (
<Redirect
to={{
pathname: '/',
state: { from: props.location }
}}
/>
)
}
/>
);
export default PrivateRoute;
登錄.js
localStorage.setItem("isAuthenticated", true);
this.props.history.push('/dashboard');
任何幫助,將不勝感激。 謝謝!
你可以試試嗎?
PrivateRoute.js
const PrivateRoute = ({ component: Component, authenticated, ...rest }) => {
console.log("authenticated",authenticated)//is it true or false?
if (authenticated=="true")
return (
<Route {...rest}>
{" "}
<Component {...rest} {...props} />
</Route>
);
else
return (
<Redirect
to={{
pathname: "/",
state: { from: props.location },
}}
/>
);
};
export default PrivateRoute;
所以,我找到了解決方案。
authenticated={localStorage.getItem("isAuthenticated")}
以上是在應用程序引導程序中調用該方法,因此我將 null 的值存儲在我的已驗證變量中,因此,我將其更改為箭頭 function 並傳遞參數而不調用它,如下所示:
authenticated={() => localStorage.getItem("isAuthenticated")}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.