Redux Toolkit与React Native报错:TypeError: undefined is not an object
Redux Toolkit持久化存储报错:TypeError: undefined is not an object (evaluating 'state.favorites.favorites')
问题核心原因
报错源于Redux Store结构与Selector函数、类型定义不匹配:
- Store注册Reducer时使用的键是
favoriteData,但Selector却尝试访问state.favorites.favorites,导致state.favorites为undefined,触发报错。 - 类型定义
IFavoriteState与实际Store结构不一致,进一步加剧了逻辑混淆。
修复步骤
1. 修正Selector函数
修改reducer.ts中的favoriteStateData选择器,使其匹配Store中真实的Reducer键名:
// reducer.ts export const favoriteStateData = (state: IFavoriteState) => state.favoriteData.favorites; // 将state.favorites改为state.favoriteData
2. 修正类型定义IFavoriteState
更新types.ts中的IFavoriteState,使其对应Store的真实结构:
// types.ts export interface IFavoriteState{ favoriteData: IFavorite // 替换原有的favorites嵌套结构 }
3. 清除旧持久化数据(可选但推荐)
由于之前可能已用错误结构持久化过数据,建议在开发环境临时执行AsyncStorage.clear(),避免旧数据引发的结构冲突。可在App组件初始化时添加:
// app.tsx(仅开发测试用,验证后移除) import { useEffect } from 'react'; import AsyncStorage from "@react-native-async-storage/async-storage"; export default function App() { // ...其他代码 useEffect(() => { AsyncStorage.clear(); }, []); // ...其他代码 }
验证修复
完成上述修改后,Selector可正确访问Store中的favorites数组,持久化功能也能正常运行。
内容的提问来源于stack exchange,提问作者LeoMouraIOT
相关产品推荐
相关产品推荐

