[英]localStorage values are set to undefined after refreshing the page
I am trying to integrate previous information from localStorage
into the DOM
so the user can see it after re-visiting the page in the same browser.我正在尝试将
localStorage
中的先前信息集成到DOM
中,以便用户在同一浏览器中重新访问页面后可以看到它。 For some reason, reloading sets the major
and declared
properties in localStorage
to undefined
.出于某种原因,重新加载
localStorage
中的major
属性和declared
属性设置为undefined
。
Could anyone tell me why this is happening and how I can fix it?谁能告诉我为什么会发生这种情况以及我该如何解决? Here is my code:
这是我的代码:
import React, { useState, useReducer, useEffect, useRef } from "react";
import MajorStatus from "./MajorStatus";
import ClassType from "./ClassType";
import styles from "/styles/ClassSearch.module.css";
function UserInfo() {
const [currentMajor, setCurrentMajor] = useState();
const [currentlyDeclared, setIsCurrentlyDeclared] = useState();
useEffect(() => {
localStorage.setItem("declared", currentlyDeclared);
localStorage.setItem("major", currentMajor);
}, [currentMajor, currentlyDeclared]);
useEffect(() => {
let storedDeclarationStatus = localStorage.getItem("declared");
let storedMajor = localStorage.getItem("major");
let declarationLabel = storedDeclarationStatus ? "Declared" : "Undeclared";
declaredRef.current.setValue({
label: declarationLabel,
value: storedDeclarationStatus,
});
majorRef.current.setValue({
label: storedMajor,
value: storedMajor,
});
}, []);
let declaredRef = useRef();
let majorRef = useRef();
function onChangeMajorHandler(userInput) {
setCurrentMajor(userInput.value.major);
console.log("Current input major: " + userInput.value.major);
}
function onChangeDeclaredHandler(userInput) {
setIsCurrentlyDeclared(userInput.value.declared);
console.log("Current input declaration: " + userInput.value.declared);
}
function onSubmitHandler(event) {
event.preventDefault();
}
return (
<form className={styles.userInfo} method="post" onSubmit={onSubmitHandler}>
<MajorStatus
onChangeMajorHandler={onChangeMajorHandler}
onChangeDeclaredHandler={onChangeDeclaredHandler}
majorRef={majorRef}
declaredRef={declaredRef}
/>
<ClassType />
<button
type="submit"
name="submitUserInfo"
className={styles.submitUserInfoButton}
>
Search
</button>
</form>
);
}
export default UserInfo;
The problem is caused by the first useEffect
, it's running before the second one when the component gets mounted, and it's setting the values in localStorage
to the initial values of your states, undefined
since you didn't set any when calling useState
.问题是由第一个
useEffect
引起的,它在安装组件时在第二个之前运行,并且它将localStorage
中的值设置为您的状态的初始值, undefined
,因为您在调用useState
时没有设置任何值。 One way to avoid this issue is:避免此问题的一种方法是:
useEffect(() => {
if (currentlyDeclared) {
localStorage.setItem("declared", currentlyDeclared);
}
if (currentMajor) {
localStorage.setItem("major", currentMajor);
}
}, [currentMajor, currentlyDeclared]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.