在下面的代码中,为什么useEffect关心变量是否为空?



在下面的代码中,变量最初被设置为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;

相关内容

  • 没有找到相关文章

最新更新