【问题标题】:How to Redirect in React based on State如何在 React 中根据状态重定向
【发布时间】:2021-09-13 11:33:52
【问题描述】:

我正在使用 useEffect 获取用户的登录状态 if (userLoggedIn === false) 然后我想立即重定向到登录路径,否则显示仪表板。

我的问题是仪表板显示一瞬间然后重定向发生!我在 console.log 中测试了 userLoggedIn,第一次打印两次未定义值,然后打印 false...

我认为发生这种情况是因为状态的值是 (userLoggedIn) 并没有设置在首位,但即使我将它设置为 false 例如它也会做完全相同的事情..

我正在使用来自后端的 useEffect 获取 (userLoggedIn) 值,我的代码是:-

import { useState, useEffect } from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect
} from "react-router-dom";
import Axios from "axios";

import ModalNotFound from "../../components/Modal/ModalNotFound";

//views
import Home from "./views/Home";
import Menu from "./views/Menu";
import Orders from "./views/Orders";
import AddFood from "./views/AddFood";
import EditFood from "./views/EditFood";
import About from "./views/About";

const DashboardContainer = () => {
  document.body.classList.add("dashboard");

  const [userLoggedIn, setUserLoggedIn] = useState(false);

  Axios.defaults.withCredentials = true;

  useEffect(() => {
    Axios.get("http://dev.com:3001/login")
      .then(({ data }) => setUserLoggedIn(data.loggedIn))
      .catch((err) => console.error(err));

    return () => setUserLoggedIn(); // cleanup: set the value to nothing
  }, []);

  console.log(userLoggedIn);

  return (
    <>
      {userLoggedIn === false ? (
        <Redirect to='/login' />
      ) : (
        <Router>
          <Switch>
            <Route exact strict path='/dashboard' component={Home} />
            {/* if user accesses /dashboard/ then remove ending slash / bcuz it messes the links*/}
            <Route exact strict path='/dashboard/'>
              <Redirect to='/dashboard' />
            </Route>
            <Route exact strict path='/dashboard/menu' component={Menu} />
            <Route exact strict path='/dashboard/orders' component={Orders} />
            <Route
              exact
              strict
              path='/dashboard/add-food'
              component={AddFood}
            />
            <Route
              exact
              strict
              path='/dashboard/edit-food'
              component={EditFood}
            />
            <Route exact strict path='/dashboard/about' component={About} />

            <Route path='*' component={ModalNotFound} />
          </Switch>
        </Router>
      )}
    </>
  );
};

export default DashboardContainer;

对于端点/后端 (http://dev.com:3001/login),我正在使用以下代码:-

module.exports = (req, res) => {
  if (req.session.user) {
    res.send({ loggedIn: true, user: req.session.user });
  } else {
    res.send({ loggedIn: false });
  }
};

【问题讨论】:

  • 我建议在 API 获取数据时使用覆盖屏幕的闪屏/加载器。在发送请求和获取数据之间总会有时间(甚至是毫秒)。仅当 userLoggedIn 为 true 时才隐藏加载程序或启动程序,因此加载将显示直到重定向

标签: node.js reactjs express express-session


【解决方案1】:

正如你所说,console.log 打印两次,第一次 userLoggedIn 未定义。仪表板在这里显示,因为 userLoggedIn 不等于 false 它转到显示仪表板的代码。

为了防止第一次渲染,你可以包装你的 return

return (
        { userLoggedIn !== undefined && {/* your code */} }
       );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    相关资源
    最近更新 更多