简体   繁体   English

React Router Dom 路由条件渲染

[英]React Router Dom Route Conditional Rendering

I trie to render a certain route if a token is valid, previously set when logging in, if not valid i redirect the user to the home page.如果令牌有效,我会尝试呈现某个路由,之前在登录时设置,如果无效,我会将用户重定向到主页。 But when i compile it kept showing a blank page.但是当我编译它时,它一直显示一个空白页。 The registered token aims at protecting routes, so when user who was not logged in can't access the '/auth' endpoint.注册的令牌旨在保护路由,因此当未登录的用户无法访问“/auth”端点时。

Here is the code:这是代码:

在此处输入图像描述

If there is a change in cookies , React would not be informed, hence your component will not be rendered to render the right Route .如果cookies发生变化,则不会通知 React,因此您的组件将不会被渲染以渲染正确的Route A React component only updates when its props or states changes, or the parent component renders it directly. React 组件仅在其 props 或 state 发生变化时更新,或者父组件直接渲染它。

You can listen to cookies and set a state to notify React that cookies has changed.您可以收听 cookies 并设置 state 以通知 React cookies 已更改。

I found another solution for this problem and it works fine actually.我为这个问题找到了另一个解决方案,它实际上工作得很好。

Code:代码:

在此处输入图像描述

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

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