
在React中,组件的状态(通过useState或useReducer管理)是与组件实例绑定的。当用户进行页面刷新(F5或地址栏回车)时,整个React应用会被重新加载,所有组件实例都会被销毁并重新创建。这意味着,所有通过useState定义的状态都会被重置为其初始值。
以提供的认证上下文(AuthContext)为例:
// AuthProvider 简化版
export const AuthProvider = ({ children }) => {
const [auth, setAuth] = useState({}); // 问题所在:每次刷新都会重置为 {}
const [loading, setLoading] = useState(true);
useEffect(() => {
const storedToken = localStorage.getItem("accessToken");
const storedRoles = localStorage.getItem("roles");
const storedId = localStorage.getItem("userId");
if (storedToken && storedRoles && storedId) {
const token = JSON.parse(storedToken);
const roles = JSON.parse(storedRoles);
const id = JSON.parse(storedId);
setAuth({ token: token, roles: roles, id: id });
}
setLoading(false);
}, []); // 此 useEffect 在组件首次渲染后运行
return (
<AuthContext.Provider value={{ auth, setAuth, loading }}>
{children}
</AuthContext.Provider>
);
};上述代码的问题在于,const [auth, setAuth] = useState({}); 这一行会在每次 AuthProvider 组件挂载时(即页面刷新后)将 auth 状态初始化为一个空对象 {}。尽管 useEffect 会在组件首次渲染后尝试从 localStorage 中加载数据并更新 auth,但在 useEffect 执行完成之前,auth 仍然是初始的空对象。如果其他组件(如 Exercises)在此时尝试访问 auth.id,它将得到 undefined 或 null,导致逻辑错误。
例如,在 Exercises 组件中:
// Exercises 组件片段
function Exercises() {
const { auth, loading } = useAuth(); // auth 此时可能为 {}
// ...
useEffect(() => {
// ...
// 如果 auth.id 此时为 undefined,getUserExercises(undefined) 将失败
api.getUserExercises(auth.id).then((response) => {
setRequests(response.data);
});
}, [id, auth.id]); // 依赖 auth.id
// ...
const onSubmit = (e) => {
e.preventDefault();
console.log("User id" + auth.id); // auth.id 此时可能为 undefined
const updatedExerciseData = {
...exerciseData,
userId: auth.id, // userId 可能为 undefined
date: new Date(),
};
// ...
};
}要解决页面刷新导致的状态丢失问题,我们需要将认证信息存储在浏览器客户端的持久化存储中,并在组件初始化时从该存储中读取。localStorage 是一个常见的选择。关键在于,useState 的初始值应该直接从 localStorage 中获取,而不是在 useEffect 中异步设置。
以下是改进后的 AuthProvider 代码:
import { createContext, useState, useEffect } from "react";
const AuthContext = createContext({});
// 辅助函数:从 localStorage 获取初始认证数据
const getInitialAuth = () => {
try {
const storedToken = localStorage.getItem("accessToken");
const storedRoles = localStorage.getItem("roles");
const storedId = localStorage.getItem("userId");
if (storedToken && storedRoles && storedId) {
// 确保所有必要的数据都存在
const token = JSON.parse(storedToken);
const roles = JSON.parse(storedRoles);
const id = JSON.parse(storedId);
return { token, roles, id };
}
} catch (error) {
console.error("Failed to parse auth data from localStorage", error);
// 如果解析失败,可能是数据损坏,清除 localStorage
localStorage.removeItem("accessToken");
localStorage.removeItem("roles");
localStorage.removeItem("userId");
}
return {}; // 如果没有有效数据,返回空对象
};
export const AuthProvider = ({ children }) => {
// 1. useState 的初始值设置为一个函数,该函数在组件首次渲染时执行一次,从 localStorage 获取数据
const [auth, setAuth] = useState(getInitialAuth);
// 2. loading 状态可以根据同步的 localStorage 读取结果来初始化
const [loading, setLoading] = useState(false); // 因为 getInitialAuth 是同步的
// 3. 使用 useEffect 监听 auth 状态的变化,并将其持久化到 localStorage
useEffect(() => {
if (auth.token && auth.roles && auth.id) {
// 当 auth 状态更新时(例如登录成功),将其保存到 localStorage
localStorage.setItem("accessToken", JSON.stringify(auth.token));
localStorage.setItem("roles", JSON.stringify(auth.roles));
localStorage.setItem("userId", JSON.stringify(auth.id));
} else {
// 如果 auth 状态变为空(例如用户登出),清除 localStorage
localStorage.removeItem("accessToken");
localStorage.removeItem("roles");
localStorage.removeItem("userId");
}
}, [auth]); // 依赖 auth 对象,当 auth 发生变化时触发
// 登出函数,用于清除认证状态和 localStorage
const logout = () => {
setAuth({});
localStorage.removeItem("accessToken");
localStorage.removeItem("roles");
localStorage.removeItem("userId");
};
return (
<AuthContext.Provider value={{ auth, setAuth, loading, logout }}>
{children}
</AuthContext.Provider>
);
};
export default AuthContext;关键改进点解释:
在 Exercises 或其他消费 useAuth 的组件中,由于 auth 状态在组件挂载时就已从 localStorage 初始化,因此 auth.id 在大多数情况下会立即可用(如果用户已登录)。
// Exercises 组件改进
import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import styles from "./ExercisePage.module.css";
import api from "../../apis/requestService";
import useAuth from "../../hooks/useAuth";
function Exercises() {
const { setAuth, auth, loading } = useAuth(); // auth.id 此时应已正确初始化
const { id } = useParams();
const navigate = useNavigate();
const [requests, setRequests] = useState([]);
const [exerciseData, setExerciseData] = useState({
weight: "",
reps: "",
exerciseId: id,
date: null,
});
const [err, setErr] = useState("");
const [popupStyle, showPopup] = useState("hide");
const { weight, reps } = exerciseData;
useEffect(() => {
setExerciseData((prevData) => ({
...prevData,
exerciseId: id,
date: new Date(),
}));
// 确保 auth.id 存在且有效才进行 API 调用
if (auth.id) {
api.getUserExercises(auth.id).then((response) => {
setRequests(response.data);
}).catch(error => {
console.error("Error fetching user exercises:", error);
// 处理错误,例如导航到登录页
});
} else if (!loading) { // 如果 auth.id 不存在且认证加载已完成,可能需要重定向
console.warn("Auth ID not available, user might not be logged in.");
// navigate('/login'); // 示例:如果需要强制登录
}
}, [id, auth.id, loading]); // 依赖 auth.id 和 loading 状态
const onInputChange = (e) => {
setExerciseData({ ...exerciseData, [e.target.name]: e.target.value });
};
const onSubmit = (e) => {
e.preventDefault();
if (!auth.id) {
setErr("User not authenticated. Please log in.");
popup();
return;
}
console.log("User id: " + auth.id);
const updatedExerciseData = {
...exerciseData,
userId: auth.id,
date: new Date(),
};
api
.createRequest(updatedExerciseData)
.then((response) => {
if (response.data.id) {
// 再次确保 auth.id 存在
return api.getUserExercises(auth.id);
} else {
throw new Error("An error occurred while creating the request.");
}
})
.then((response) => {
setRequests(response.data);
setExerciseData({ ...updatedExerciseData, weight: "", reps: "" });
})
.catch((error) => {
console.error(error);
setErr("An error occurred while creating the request.");
popup();
});
};
const popup = () => {
showPopup("exercise-popup");
setTimeout(() => showPopup("hide"), 3000);
};
// 如果数据仍在加载,可以显示加载指示器
if (loading) {
return <div>Loading authentication data...</div>;
}
// 渲染逻辑...
return (
<div className={styles.wrapper}>
{/* ... (原有渲染代码) ... */}
<div className={styles.content}>
{requests.length > 0 ? (
requests.map((request, index) => (
<div key={index} className={styles.requestBox}>
<div className={styles.requestDetails}>
<h2>{request.exercise.name}</h2>
<p>{request.exercise.description}</p>
</div>
<img
src={request.exercise.imageUrl}
alt={request.exercise.name}
/>
<div className={styles.requestInfo}>
<p>Weight: {request.weight} kg</p>
<p>Reps: {request.reps}</p>
<p>Date: {new Date(request.date).toLocaleDateString()}</p>
</div>
</div>
))
) : (
<p>No exercises assigned yet.</p>
)}
</div>
<form onSubmit={(e) => onSubmit(e)} className={styles.exerciseForm}>
<h1 className={styles.h1Text}>
Set <br /> Exercise
</h1>
<div className={styles.inputContainer}>
<label htmlFor="weight" className={styles.inputLabel}>
Enter weight
</label>
<input
id="weight"
name="weight"
type="number"
value={weight}
min="0"
onChange={onInputChange}
className={styles.inputBox}
/>
</div>
<div className={styles.inputContainer}>
<label htmlFor="reps" className={styles.inputLabel}>
Enter reps
</label>
<input
id="reps"
name="reps"
type="number"
value={reps}
min="0"
onChange={onInputChange}
className={styles.inputBox}
/>
</div>
<button className={styles.exerciseBtn} type="submit">
+
</button>
<div className={popupStyle}>
<h3>{err}</h3>
</div>
</form>
</div>
);
}
export default Exercises;重要注意事项:
通过在 useState 初始化时直接读取 localStorage,并在 useEffect 中监听状态变化以同步更新 localStorage,我们可以有效地解决 React 应用中认证状态在页面刷新后丢失的问题。这种模式确保了用户体验的连贯性,并为需要持久化状态的场景提供了可靠的解决方案。在实际应用中,请根据项目的具体安全需求和复杂度,选择最合适的持久化策略。
以上就是React 应用中认证状态刷新丢失的解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号