在下面的代码中,变量最初被设置为null,因为它当前不存在于本地存储中。然而,useEffect抱怨TypeError: Cannot read properties of undefined (reading 'null')
,并指出isDeclared
变量在其依赖关系。为什么useEffect拒绝一个值为null的变量?我只是想在第一次渲染时将本地存储中的isDeclared
键的值设置为null
。谢谢!
import React, { useEffect, useState } from "react";
function ClassSearch() {
const [isDeclared, setIsDeclared] = useState(
localStorage.getItem("isDeclared")
);
const [major, setMajor] = useState(localStorage.getItem("major"));
useEffect((isDeclared) => {
return localStorage.setItem("isDeclared", isDeclared);
})[isDeclared];
useEffect((major) => {
return localStorage.setItem("major", major);
})[major];
return <div>{`This isn't operational yet`}</div>;
}
export default ClassSearch;
你的代码有语法错误,useEffect的错误返回,以及依赖项的使用,
import React, { useEffect, useState } from "react";
function ClassSearch() {
const [isDeclared, setIsDeclared] = useState(
localStorage.getItem("isDeclared")
);
const [major, setMajor] = useState(localStorage.getItem("major"));
useEffect(
(isDeclared) => {
console.log(1);
localStorage.setItem("isDeclared", isDeclared);
},
[isDeclared]
);
useEffect(
(major) => {
console.log(1);
localStorage.setItem("major", major);
},
[major]
);
return <div>{`This isn't operational yet`}</div>;
}
export default ClassSearch;