简体   繁体   English

反应:私人路线不导航

[英]React: private route not navigating

I am using a private route to navigate to a route after the user has logged in. However, I am facing an issue.用户登录后,我正在使用私有路由导航到某个路由。但是,我遇到了一个问题。 I don't know why but my router is not transitioning to the desired route.我不知道为什么,但我的路由器没有转换到所需的路由。 Here's my code:这是我的代码:

Routes.js路由.js

...
...
<PrivateRoute
  authenticated={localStorage.getItem("isAuthenticated")}
  path="/dashboard"
  component={DashBoard}
  exact
></PrivateRoute>

PrivateRoute.js 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;

Login.js登录.js

localStorage.setItem("isAuthenticated", true);
this.props.history.push('/dashboard');

Any help would be appreciated.任何帮助,将不胜感激。 Thanks!谢谢!

Can you just try it?你可以试试吗?

PrivateRoute.js 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;

So, I found the solution.所以,我找到了解决方案。

authenticated={localStorage.getItem("isAuthenticated")}

the above was invoking the method at application bootstrap due to which I was having the value of null being stored in my authenticated variable so, I changed it to arrow function and passed the argument without invoking it like below:以上是在应用程序引导程序中调用该方法,因此我将 null 的值存储在我的已验证变量中,因此,我将其更改为箭头 function 并传递参数而不调用它,如下所示:

authenticated={() => localStorage.getItem("isAuthenticated")}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM