当localstorage值更改时,如何更改状态?
当localstorage
值更改时,如何更改状态。例如,我有一个语言切换按钮,例如法语和英语,当我单击英语时,它将存储在localStorage
时,当我单击英语时,它也将。
当我单击法语时,整个项目需要用法语查看时,当我单击英语时,是否要这样做,所以当我更新localStorage
时,我该如何更改状态?
<button onclick={()=>localStorage.setItem("language",'english')}>English</button>
<button onclick={()=>localStorage.setItem("language",'french')}>French</button>
let language;
if (typeof window !== "undefined") {
if (localStorage.getItem("language") === null) {
language = "english";
}
if (localStorage.getItem("language") !== null) {
language = localStorage.getItem("language");
}
}
const [langu, setLangua] = useState(language);
console.log(langu);
How to change state when localStorage
value changed. For example, I have a language switching button, like French and English, when I click English, it will be storing to localStorage
, when I click English it will also.
When I click the French the whole project need to see in French, also when I click English, want to do like that, it So how can I change state when I update localStorage
?
<button onclick={()=>localStorage.setItem("language",'english')}>English</button>
<button onclick={()=>localStorage.setItem("language",'french')}>French</button>
let language;
if (typeof window !== "undefined") {
if (localStorage.getItem("language") === null) {
language = "english";
}
if (localStorage.getItem("language") !== null) {
language = localStorage.getItem("language");
}
}
const [langu, setLangua] = useState(language);
console.log(langu);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实现这一目标的一种方法不会改变您当前的结构,首先将按钮更改为此:
然后在具有
setLangua
和languy
useffect
将收听localstorage
中的更改并更新状态:One way to achieve this that wouldn't change that much your current structure is first to change your buttons to this:
And then set up inside the component where you have
setLangua
andlangu
anuseEffect
that would listen to changes in thelocalStorage
and update the state:您需要在
使用
挂钩中设置它,并且具有空依赖性,仅在组件安装时才会运行。you need set it in
useEffect
hook, with empty dependences, it will run only when the component mount.您可以在将其放入本地存储中同时setlangua。或者,您可以订阅本地存储更改使用效果钩。
注意:这在进行更改的同一页面上无法使用 - 这实际上是使用存储在域上使用存储来同步任何更改的其他页面的一种方式。其他域上的页面无法访问相同的存储对象。
You can setLangua at the same time as putting it in local storage. Or you can subscribe to local storage changes with the useEffect hook.
Note: This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.