React useContext 在重定向后保留数据?

React useContext keep data after redirect?

我想在登录后保留用户名,以便以后访问。上下文工作正常,但在将用户重定向到主页后,上下文值消失了。

当我在登录成功后设置上下文时,它会正常工作..

谁能告诉我如何解决这个问题?

Login.js

import { useContext, useState } from "react";
import { UserContext } from "../contexts/UserContext";

const { setUser, user } = useContext(UserContext);

async function handleLogin(e) {
    e.preventDefault();

    if (username && password) {
      await fetch("http://localhost:5000/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          username: username,
          password: password,
        }),
      })
        .then((response) => response.json())
        .then((data) => {
          if (data.error) {
            setLoginError(data.error);
            return;
          } else {
            setUser(data);
            console.log(user);
            window.location.assign("/");
          }
        })
    }
  }

Home.js

import React, { useContext } from "react";
import { UserContext } from "../contexts/UserContext";

const Home = () => {
  const { user } = useContext(UserContext);
  return (
    <>
      <h1>Home</h1>
      <p>{user.username}</p>
    </>
  );
};

export default Home;

App.js

import { Routes, Route } from "react-router-dom";
import { useState } from "react";

import IncludeLayout from "./helper/IncludeLayout";
import ExcludeLayout from "./helper/ExcludeLayout";
import ProtectedRoutes from "./helper/ProtectedRoutes";

import Home from "./pages/Home";
import Login from "./pages/Login";
import Users from "./pages/Users";

import { UserContext } from "./contexts/UserContext";

function App() {
  const [user, setUser] = useState({});

  return (
    <ThemeProvider theme={theme}>
      <UserContext.Provider value={{ user, setUser }}>
        <Routes>
          <Route element={<ExcludeLayout />}>
            <Route exact path="login" element={<Login />} />
          </Route>
          <Route element={<ProtectedRoutes />}>
            <Route element={<IncludeLayout />}>
              <Route exact path="/" element={<Home />} />
              <Route exact path="/users" element={<Users />} />
            </Route>
          </Route>
        </Routes>
      </UserContext.Provider>
    </ThemeProvider>
  );
}

export default App;

使用 react-router-dom

中的 useNavigate
import { useContext, useState } from "react";
import { UserContext } from "../contexts/UserContext";
import { useNavigate } from "react-router-dom";

const navigate = useNavigate(); 
const { setUser, user } = useContext(UserContext);

async function handleLogin(e) {
    e.preventDefault();
    

    if (username && password) {
      await fetch("http://localhost:5000/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          username: username,
          password: password,
        }),
      })
        .then((response) => response.json())
        .then((data) => {
          if (data.error) {
            setLoginError(data.error);
            return;
          } else {
            setUser(data);
            console.log(user);
            navigate("/");
            //window.location.assign("/");
          }
        })
    }
  }

在 Samathingamajig 的帮助下,我找到了适合我的解决方案:

import { useNavigate } from "react-router-dom";
const navi = useNavigate();
navi("/");

而不是使用 useHistory。

它不起作用的原因是您没有将数据保存到浏览器存储中,因此当路由到另一个页面时,数据将丢失没有解决方法它只是保存数据或保存某种身份验证令牌所以稍后你可以检查是否有令牌,如果有将它发送到服务器以获取用户详细信息,如果你使用 useEffct 执行此操作,然后将数据保存到它将工作的上下文中,你可以在 app.js 这样,只要用户路由到任何页面,useEffect 就会触发,如果您想要此功能,请告诉我,我会详细说明并向您展示如何操作。