You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AsyncStorage数据更新后需重启APP才能显示,求代码问题排查

问题:添加AsyncStorage项目后需重启应用才能看到更新

我目前能正常展示存储在AsyncStorage中的信息,但每次向列表添加新项目后,必须重启应用才能看到更新后的内容。我知道应该使用useEffect Hook,但尝试多种方法仍未解决问题,麻烦帮忙排查代码问题,我自己也会继续研究。


存储数据到AsyncStorage的代码

AsyncStorage.setItem(
  `listeElements:${data["fk_produit_id"]}`,
  JSON.stringify(data["fk_produit_id"])
);

获取数据到useState数组的代码

const getProduct = async (id) => {
  if (id) {
    dispatch(authAction.Favorite(id))
      .then((response) => {
        const newArray = response.array;

        setInformations(newArray);
      })
      .catch((error) => {
        console.error(error);
      });
  } else {
    const keys = await AsyncStorage.getAllKeys();
    let tempInformations = [...informations];
    if (keys) {
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        if (key.startsWith("listeElements")) {
          const value = await AsyncStorage.getItem(key);
          await fetch(
            `http://ip_adress/api/users/favorite?value=${value}`,
            {
              method: "GET",
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
            .then((response) =>
              response.json().then((responseJson) => {
                const newArray = responseJson.array;
                tempInformations = [...tempInformations, ...newArray];
              })
            )
            .catch((e) => console.log(e));
        }
      }
      setInformations(tempInformations);
    }
  }
};

useEffect(() => {
  getProduct(decoded._id);
  const intervalId = setInterval(() => {
    setRefreshTime(Date.now());
  }, 3000);
  return () => clearInterval(intervalId);
}, [decoded]);

问题排查与解决方法

核心问题

当前代码仅在组件挂载(decoded变化)时调用getProduct获取一次数据,添加新项目后没有主动触发数据刷新,因此必须重启应用才能重新读取AsyncStorage的新内容。

具体修复步骤

  1. 添加项目后主动触发刷新
    在执行AsyncStorage.setItem完成后,直接调用getProduct重新获取最新数据,更新状态:

    AsyncStorage.setItem(
      `listeElements:${data["fk_produit_id"]}`,
      JSON.stringify(data["fk_produit_id"])
    ).then(() => {
      // 添加完成后立即刷新列表
      getProduct(decoded._id);
    }).catch(err => console.error(err));
    
  2. 优化useEffect依赖(可选)
    若想通过refreshTime定时刷新,需将其加入useEffect的依赖数组,确保每次refreshTime变化时重新调用getProduct:

    useEffect(() => {
      getProduct(decoded._id);
      const intervalId = setInterval(() => {
        setRefreshTime(Date.now());
      }, 3000);
      return () => clearInterval(intervalId);
    }, [decoded, refreshTime]); // 加入refreshTime依赖
    

    优先推荐第一种主动调用的方式,比定时轮询更高效。

  3. 修复状态更新的潜在问题
    在getProduct的else分支中,tempInformations初始化依赖当前informations快照,异步操作完成后可能导致状态更新丢失。可改为函数式更新或重新构建完整列表:

    // 方式1:使用函数式更新
    setInformations(prev => [...prev, ...tempInformations]);
    
    // 方式2:重新构建完整列表,不依赖当前状态
    let tempInformations = []; // 初始化空数组,从AsyncStorage重新获取所有数据
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 11:27:33