IF-ELSE在React中运行两次

发布于 2025-02-10 21:15:12 字数 2809 浏览 0 评论 0原文

我在尝试进入不同页面时有问题,例如,IF-else在IF和1次的情况下运行两次,例如:我在仪表板路由中添加了一个日志,而当“ IsauseDicatienated”为“真实”是正确的,我会重定向到 /仪表板,但我也同时获得了控制台登录(如果我有导航而不是日志,我会两次重定向,这是我要解决的问题)

import React, { Fragment, useState, useEffect } from "react";
import './App.css';
import "react-toastify/dist/ReactToastify.css";
import {BrowserRouter as Router, Routes, Route, Navigate} from "react-router-dom";
import { toast } from "react-toastify";

//components
import Login from "./components/Login";
import Register from "./components/Register";
import Dashboard from "./components/Dashboard";
import Home from "./components/Home";
import Auction from "./components/Auction";
//import Home from "./components/Home";


function App() {
  const checkAuthenticated = async () => {
    try {
      const res = await fetch("http://localhost:5000/auth/is-verify", {
        method: "GET",
        headers: { token: localStorage.token }
      
      });

      const parseRes = await res.json();

      parseRes === true ? setIsAuthenticated(true) : setIsAuthenticated(false);
    } catch (err) {
      console.error(err.message);
    }
  };

  useEffect(() => {
    checkAuthenticated();
  }, []);

  const [isAuthenticated, setIsAuthenticated] = useState(false);

  const setAuth = boolean => {
    setIsAuthenticated(boolean);
  };
  
//<Route path = '/auth' element = {<Auth/>} />
  return (
    <Fragment>
      <Router>
        <div className="container">
          <Routes>
          <Route path='/home' element = {
                isAuthenticated ? (
                  <Home setAuth={setAuth}  />
                ) : (
                  <Navigate to="/login" />
                )
              } />
            <Route path='/login' element = {
                !isAuthenticated ? (
                  <Login setAuth={setAuth}  />
                ) : (
                  <Navigate to="/home" />
                )
              } />
            <Route path='/register' element = {
                !isAuthenticated ? (
                  <Register setAuth={setAuth}  />
                ) : (
                  <Navigate to="/home" />
                )
              } />
           **<Route path='/dashboard' element = {
                isAuthenticated ? (
                  <Dashboard setAuth={setAuth}  />
                ) : (
                  console.log("dashboard")
                )
              } />**
              
              <Route path='/auction' element = {
               
                  <Auction setAuth={setAuth}  />
              
        
              } />
          </Routes>
        </div>
      </Router>
    </Fragment>
  );
};

export default App;

I have a problem when trying to go to different pages, the inline if-else runs twice 1 time for if and 1 time for else, for example: I added a log to the dashboard route and when "isAuthenticated" is true i get redirected to /dashboard but i also get the console log at the same time(if i have Navigate instead of log i get redirected twice that is the problem i am trying to fix) any idea why this is happening ?

import React, { Fragment, useState, useEffect } from "react";
import './App.css';
import "react-toastify/dist/ReactToastify.css";
import {BrowserRouter as Router, Routes, Route, Navigate} from "react-router-dom";
import { toast } from "react-toastify";

//components
import Login from "./components/Login";
import Register from "./components/Register";
import Dashboard from "./components/Dashboard";
import Home from "./components/Home";
import Auction from "./components/Auction";
//import Home from "./components/Home";


function App() {
  const checkAuthenticated = async () => {
    try {
      const res = await fetch("http://localhost:5000/auth/is-verify", {
        method: "GET",
        headers: { token: localStorage.token }
      
      });

      const parseRes = await res.json();

      parseRes === true ? setIsAuthenticated(true) : setIsAuthenticated(false);
    } catch (err) {
      console.error(err.message);
    }
  };

  useEffect(() => {
    checkAuthenticated();
  }, []);

  const [isAuthenticated, setIsAuthenticated] = useState(false);

  const setAuth = boolean => {
    setIsAuthenticated(boolean);
  };
  
//<Route path = '/auth' element = {<Auth/>} />
  return (
    <Fragment>
      <Router>
        <div className="container">
          <Routes>
          <Route path='/home' element = {
                isAuthenticated ? (
                  <Home setAuth={setAuth}  />
                ) : (
                  <Navigate to="/login" />
                )
              } />
            <Route path='/login' element = {
                !isAuthenticated ? (
                  <Login setAuth={setAuth}  />
                ) : (
                  <Navigate to="/home" />
                )
              } />
            <Route path='/register' element = {
                !isAuthenticated ? (
                  <Register setAuth={setAuth}  />
                ) : (
                  <Navigate to="/home" />
                )
              } />
           **<Route path='/dashboard' element = {
                isAuthenticated ? (
                  <Dashboard setAuth={setAuth}  />
                ) : (
                  console.log("dashboard")
                )
              } />**
              
              <Route path='/auction' element = {
               
                  <Auction setAuth={setAuth}  />
              
        
              } />
          </Routes>
        </div>
      </Router>
    </Fragment>
  );
};

export default App;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文