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

React Native中useState设置状态后未更新问题求助

问题原因及解决方案

1. setState 是异步操作,直接打印无法获取最新状态

React 的 setState(包括 useState 的更新函数)是异步执行的,调用 setFavoritesExercices 后,favoritesExercices 不会立即更新,所以此时打印的还是初始的空数组。

2. 状态更新逻辑存在错误

从调试结果看,你从 AsyncStorage 取出的 ex 本身就是目标数组,但你用 [...favoritesExercices, ex] 会把整个 ex 数组作为单个元素嵌套进原数组;另外,retrieveData 是在空依赖的 useEffect 中调用的,它捕获的 favoritesExercices 始终是组件初始化时的空数组,无法获取后续的状态更新。


修正后的代码

const [favoritesExercices, setFavoritesExercices] = useState([]);

const retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('favoritesExercices');
    if (value !== null) {
      const ex = JSON.parse(value);
      // 直接设置为取出的完整数组(恢复本地存储的列表)
      setFavoritesExercices(ex);
    }
  } catch (e) {
    console.error(e);
  }
}

useEffect(() => {
  retrieveData();
}, []);

// 监听状态变化,在状态更新完成后打印
useEffect(() => {
  console.log(favoritesExercices);
}, [favoritesExercices]);

特殊场景说明

如果你的需求是追加本地存储的数组到现有状态(而非直接替换),要使用函数式更新来确保拿到最新状态:

setFavoritesExercices(prevState => [...prevState, ...ex]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:22:07