You need to enable JavaScript to run this app. 如何用React Hooks更新localStorage中存储的数组 解决点击重写问题
优惠活动
大模型
产品
解决方案
定价
更多

如何用React Hooks更新localStorage中存储的数组 解决点击重写问题

问题根因

你遇到的写入覆盖问题,本质来自两个实现缺陷:

  • 现有useLocalStorage是每个组件实例独立维护状态的:每个SearchedCity组件挂载时只会从localStorage读一次对应key的初始值,之后各自持有一份独立的state副本,完全感知不到其他组件对同一个key的写入。比如多个城市卡片同时存在时,你点击某一个卡片拿到的prev值是自己组件挂载时的旧值,基于这个旧值拼接的结果自然会把之前其他操作写入的内容全部覆盖。
  • setValue处理函数式更新时,取的是闭包捕获的旧state值,没有在写入前实时读取localStorage的最新存量值,极端时序下也会出现值覆盖。
调整方案

需要对自定义Hook做核心改造,实现同一个key的多实例状态共享、写入前实时读最新存量值:

  1. 把同key的状态提到模块级全局存储,避免每个组件各存一份独立副本,修改值时通知所有订阅的组件同步更新
  2. 执行写入前,先实时读取当前最新的存量值,再执行函数式拼接,彻底消除闭包旧值的影响
  3. 增加localStorage事件监听,支持跨标签页的状态同步
调整后完整代码
import React, {useEffect, useState} from  'react';
import styled from 'styled-components';

const Container = styled.div`
   background-color: white;
   display: flex;
   position: relative;
   flex-direction: column;
   align-items: center;
   justify-content: center;
   width: 100%;
   cursor: pointer;
   padding: 2rem;
   margin-top: 2rem;
   transition: all 0.2s ease;
   border-radius: 5px;
   box-shadow: 0 .1rem 1rem 5px rgba(0,0,0,0.07);
   &:hover{
     box-shadow: 0 .1rem 1rem 5px rgba(0,0,0,0.16);
     transform: translateY(-3px);
   }
`;

// 模块级全局存储:按key缓存当前值、订阅者列表,解决多实例状态独立问题
const globalCache = {};
const subscriberMap = {};

const useLocalStorage = (key, initialValue) => {
  // 初始化全局缓存中对应key的初始值
  if (!(key in globalCache)) {
    try {
      const item = window.localStorage.getItem(key);
      globalCache[key] = item ? JSON.parse(item) : initialValue;
    } catch (err) {
      console.error(err);
      globalCache[key] = initialValue;
    }
    subscriberMap[key] = new Set();
  }

  const [storedValue, setStoredValue] = useState(globalCache[key]);

  // 组件挂载时订阅当前key的变更通知
  useEffect(() => {
    const subscriber = (newVal) => setStoredValue(newVal);
    subscriberMap[key].add(subscriber);
    // 组件卸载时取消订阅
    return () => subscriberMap[key].delete(subscriber);
  }, [key]);

  // 监听跨标签页的localStorage变更
  useEffect(() => {
    const onStorageChange = (e) => {
      if (e.key === key) {
        const newVal = e.newValue ? JSON.parse(e.newValue) : initialValue;
        globalCache[key] = newVal;
        subscriberMap[key].forEach(sub => sub(newVal));
      }
    };
    window.addEventListener('storage', onStorageChange);
    return () => window.removeEventListener('storage', onStorageChange);
  }, [key, initialValue]);

  const setValue = (value) => {
    try {
      // 写入前先读最新的全局缓存值,避免闭包旧值
      const currentVal = globalCache[key];
      const valueToStore = value instanceof Function ? value(currentVal) : value;
      // 更新全局缓存
      globalCache[key] = valueToStore;
      // 同步所有订阅的组件更新state
      subscriberMap[key].forEach(sub => sub(valueToStore));
      // 写入localStorage
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (err) {
      console.error(err);
    }
  };

  return [storedValue, setValue];
};

const SearchedCity = (props) => {
  const [storedId, setId] = useLocalStorage('ids', []); 

  let handleId = () => {
    setId(prev => {
      // 可选优化:避免重复存储相同的城市ID
      if (prev.includes(props.cityId)) return prev;
      return [...prev, props.cityId];
    });
  }

  return (
     <Container onClick={handleId}>
         {props.children}
     </Container>
  )
}

export default SearchedCity;
效果说明

调整后,不管页面上同时渲染多少个SearchedCity组件,所有对ids这个key的写入都会基于localStorage的最新存量值做拼接,不会出现互相覆盖的问题;跨标签页操作localStorage时,当前页面的组件状态也会自动同步。

内容的提问来源于stack exchange,提问作者Roni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.27 06:36:04