如果本地存储上有项目,我想将 itemStatus
的默认值设置为 true
。
而且我认为我可以通过从本地存储中检查来做到这一点,这样它就会返回自第一次渲染以来的值。但是当我编写这段代码时,它似乎根本不起作用,当我运行第一个 console.log
时,我得到了 []
,但第二个 console.log
总是返回 true
。我不确定我的代码有问题吗?或者也许我可以使用另一种方法来设置依赖于本地存储上的项目的默认值?
const checkItem = () => {
let check = localStorage.getItem("My Item");
console.log(localStorage.getItem("My Item"));
if (check !== []) {
return true;
} else {
return false;
}
};
const AppProvider = ({ children }) => {
const [itemStatus, setItemStatus] = useState(checkItem());
console.log(itemStatus);
....
}
答案 0 :(得分:1)
你可以这样做
const checkItem = () => !!localStorage.getItem("我的物品");
答案 1 :(得分:0)
localStorage.getItem()
总是返回 string
而这个:
if (check !== [])
实际上等于这个:
if ('[]' !== [])
然后你得到 true
答案 2 :(得分:0)
给你一个解决方案
const checkItem = () => {
let check = localStorage.getItem("My Item");
//First check for null then check for length
if (check && check.length) {
return true;
} else {
return false;
}
};
const AppProvider = ({ children }) => {
const [itemStatus, setItemStatus] = useState(checkItem());
console.log(itemStatus);
....
}
答案 3 :(得分:0)
你也可以像这样使用useMemo
const hasItem = useMemo(() => !!)