[英]Trying to build an eventlistener for localStorage with useEffect
I'm trying to implement an eventlistener that triggers an useEffect-function to render a shopping bag.我正在尝试实现一个事件监听器,它触发一个 useEffect 函数来呈现一个购物袋。 At the moment the shopping bag only appears after reloading the page.
目前购物袋仅在重新加载页面后出现。 This should happen instantly instead.
这应该立即发生。 I've build a sandbox for my problem: https://codesandbox.io/s/vigilant-oskar-drsvy?file=/src/App.js .
我已经为我的问题构建了一个沙箱: https://codesandbox.io/s/vigilant-oskar-drsvy?file=/src/App.js 。 When clicking the "Click it" button nothing appears but when reloading the page.
单击“单击它”按钮时,除了重新加载页面时,什么都不会出现。
Here is also the code:这里也是代码:
export default function App() {
const [storageData, setStorageData] = useState(localStorage.getItem("alert"));
useEffect(() => {
setStorageData(localStorage.getItem("alert"));
}, []);
//insert eventlistener to dependency array of useEffect
return (
<div className="App">
<button
onClick={() => {
localStorage.setItem("alert", "ShoppingBag");
}}
>
click it
</button>
<div>{storageData}</div>
</div>
);
}
You need to kind of inverse how you are doing it - when you storageData
changes, you should do localStorage.setItem
, and then you do setStorageData
and your useEffect
will pick up the change and save it.您需要反转您的操作方式 - 当您
storageData
更改时,您应该执行localStorage.setItem
,然后您执行setStorageData
并且您的useEffect
将获取更改并保存它。
https://codesandbox.io/s/naughty-herschel-469i1 https://codesandbox.io/s/naughty-herschel-469i1
import { useEffect, useState } from "react"; import "./styles.css"; export default function App() { const [storageData, setStorageData] = useState(localStorage.getItem("alert")); useEffect(() => { localStorage.setItem("alert", storageData); }, [storageData]); //insert eventlistener to dependency array of useEffect return ( <div className="App"> <button onClick={() => { setStorageData("ShoppingBag"); }} > click it </button> <div>{storageData}</div> </div> ); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.