简体   繁体   English

UseEffect 重定向导致闪烁和组件导航远离以在 React 中呈现 typescript

[英]UseEffect to redirect causes flicker and component navigation away from to render in React typescript

I am using useEffect to navigate away from a page and to another based on a certain condition.我正在使用useEffect根据特定条件从一个页面导航到另一个页面。 However, when I do this, and the condition to redirect is present, page flashes briefly before redirecting.但是,当我这样做并且存在重定向条件时,页面在重定向之前会短暂闪烁。

import authService from "../src/services/authService";

function App() {
  const [currentUserStatus, setCurrentUserStatus] = React.useState(
    authService.getCurrentUser()
  );

  const navigate = useNavigate();

  useEffect(() => {
    if (currentUserStatus == null) {
      navigate("/login");
    }
  });

  return (
    <div>
      <h1>Test</h1>
    </div>
  );
}

export default App;

With the above example, if currentUserStatus is null and the page navigates to '/login' , it will flash the <h1>Test</h1> before redirecting.在上面的例子中,如果currentUserStatus是 null 并且页面导航到'/login' ,它将在重定向之前 flash <h1>Test</h1> It's only a fraction of a second but it still occurs and is quite obvious.这只是几分之一秒,但它仍然会发生并且非常明显。

How can I prevent this or find a better way to redirect?我怎样才能防止这种情况或找到更好的重定向方法?

Keep in mind that useEffect runs after the render cycle.请记住,useEffect在渲染周期之后运行。 So, if you want to make sure that the <h1>Test</h1> content isn't revealed to a user who isn't logged into your site, make sure that you use conditional rendering as well:因此,如果您想确保<h1>Test</h1>内容不会透露给未登录您网站的用户,请确保您也使用条件呈现:

function App() {
  const [currentUserStatus, setCurrentUserStatus] = React.useState(
    authService.getCurrentUser()
  );

  const navigate = useNavigate();

  useEffect(() => {
    if (currentUserStatus == null) {
      navigate("/login");
    }
  });

  if (!currentUserStatus) return <h1>Loading...</h1>

  return (
    <div>
      <h1>Test</h1>
    </div>
  );
}

export default App;

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

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