React更新LocalStorage数据
我正在尝试更新本地主机的数据。我有2个接口“ Loggedinusers”和“用户”,一个具有默认值,另一个具有单个值。在这种情况下,它是颜色。我在这里做错了什么?我想将当前的“白色”颜色更改为“蓝色”。
useEffect(() => {
const usersIdColor = loggedInUsers.map((e) => user?.find((u) => u.id === e.id && u.color !== e.color));
if (usersIdColor) {
localStorage.setItem(
'logged_in_users',
JSON.stringify([...loggedInUsers, { id: user.id, username: user.username, tenantId: user.tenantId, color: 'blue' }])
);
}
}, []);
I'm trying to update data from the local host. I have 2 interfaces "loggedInUsers" and "user", one with a default value and the other with an individual value. In this case it is the colour. what am I doing wrong here? I would like to change the current "white" color to "blue".
useEffect(() => {
const usersIdColor = loggedInUsers.map((e) => user?.find((u) => u.id === e.id && u.color !== e.color));
if (usersIdColor) {
localStorage.setItem(
'logged_in_users',
JSON.stringify([...loggedInUsers, { id: user.id, username: user.username, tenantId: user.tenantId, color: 'blue' }])
);
}
}, []);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用此代码,您始终会向logging_in_users数组添加一个蓝色的新用户。如果您想更新logging_in_users,您需要更新数组中的值。像这样的东西(不确定你与用户的匹配程度如何:
With this code you are always going to add a new user to the logged_in_users array with the color blue. If you want to update the logged_in_users you need to update the value in the array. Something like this (Not sure how exactly you are matching the user:
为了防止添加新条目,您应该过滤在用户条目中登录的内容,并在更换中使用该值。
您还应该添加逻辑,以便像您一样使用查找,依此类推,或者甚至可以在过滤器方法中添加条件,这样您就可以在单个语句中完成所有操作。
Something like:
BTW: it's local storage.
In order to prevent adding new entries you should filter over the logged in users entry and use that value in replacement.
You should also add your logic to retrieve only the wanted user using find and so on, like you did, or you can even add conditions to the filter method, that way you could do it all in a single statement.
Something like:
BTW: it's local storage.