如何处理反应应用程序路由中的条件重定向?

How to handle conditional redirect in react app routes?

我正在为我的 React 项目使用 metronic theme,现在我正在尝试根据 api 的值进行条件重定向。我发现一个名为 Routes.js 的文件已经写入,我正在尝试更改那里。这是它的样子

 const [request, setRequest] = useState();
 const [isUserActive, setIsUserActive] = useState(false);

  useEffect(() => {
    fetch("http://82 ...")
      .then((res) => res.json())
      .then((data) => setRequest(data));
  }, []);

  useEffect(() => {
    if (request) {
      request.isUser=== true
        ? setIsUserActive(true)
        : setIsUserActive(false);
    }
  }, [request]);

  return (
    <Switch>
      <Route path="/error" component={ErrorsPage} />

      {!isUserActive ? (
        <Redirect to="error/error-v1" />
      ) : (
        <>
          <Redirect to="/" />
          <Layout>
            <BasePage />
          </Layout>
        </>
      )}
    </Switch>
  );

isUserActivetrue 时,我想转到 root 路径,但如果不是,我想转到 error pageisUserActive 现在登录

false 
false 
true

但我的项目总是重定向到 /error/error-v1,即使最终值为 true,我是否遗漏了什么?

您可能想添加另一个加载状态。原因是在当前设置下,一旦代码将您定向到 /error 端点,就无法返回,它将始终呈现错误页面。

const [request, setRequest] = useState();
// vvv this was added vvv
// vvv this was added vvv
// vvv this was added vvv
const [requestLoading, setRequestLoading] = useState(true);
const [isUserActive, setIsUserActive] = useState(false);

 useEffect(() => {
   fetch("http://82 ...")
     .then((res) => res.json())
     .then((data) => setRequest(data));
 }, []);

 useEffect(() => {
   if (request) {
     // vvv this was added vvv
     // vvv this was added vvv
     // vvv this was added vvv
     setRequestLoading(false);
     request.isUser=== true
       ? setIsUserActive(true)
       : setIsUserActive(false);
   }
 }, [request]);

 return (
   // vvv this conditional rendering was added vvv
   // vvv this conditional rendering was added vvv
   // vvv this conditional rendering was added vvv
   {!requestLoading ? <Switch>
     <Route path="/error" component={ErrorsPage} />

     {!isUserActive ? (
       <Redirect to="error/error-v1" />
     ) : (
       <>
         <Redirect to="/" />
         <Layout>
           <BasePage />
         </Layout>
       </>
     )}
   </Switch> : <div />}
 );

现在所有这一切所做的就是渲染一个 div 如果请求仍在加载,然后它会在完成后根据结果路由你