React Native集成redux-persist报错action.type undefined如何修复
报错核心原因
直接触发错误的是你在persistReducer(persistConfig, user())这行代码里,给user reducer加了括号直接执行了reducer函数,调用时没有传入action参数,导致action为undefined,读取action.type时直接抛出错误。除此之外你的代码还存在多处配置错误:
persistConfig配置键拼写错误:redux-persist识别存储引擎的配置项是小写开头的storage,你写为大写Storage会导致持久化失效- 创建store时未使用持久化包装后的reducer:你给createStore传入的是原始的user reducer,没有使用persistReducer包装生成的persistedReducer
- persistStore参数传值错误:persistStore需要接收创建完成的store实例作为入参,你直接传入了user reducer函数
- 导入导出命名不匹配:store文件导出的变量是小写
store,App.js中导入时写为大写Store,会拿到undefined值 - 代码存在语法问题:末尾有多余的反引号,不符合JS语法规范
- reducer缺少default分支:未匹配到对应action类型时没有默认返回state的逻辑,不符合Redux编写规范
修复后代码
Redux store配置文件
import { createStore } from 'redux'; import { persistStore, persistReducer } from 'redux-persist' import AsyncStorage from '@react-native-async-storage/async-storage'; // 如果你的user reducer是单独定义在../reducer/index文件中,就保留这行导入,删掉下面重复的user reducer声明 import user from '../reducer/index'; const persistConfig = { key: 'root', storage: AsyncStorage, // 修正为小写开头的storage配置键 }; // 如果已经从外部导入了user reducer,删掉这段函数声明 export function user( state = { id: '', id_karyawan: '', name: '', tema: '', presensi: '', color: '', akun: '', }, action, ) { switch (action.type) { case 'CHANGE/USER': return { ...state, ...action.payload }; default: // 补全default分支 return state; } } // 传入reducer函数引用,不要加()执行 const persistedReducer = persistReducer(persistConfig, user) // 传入包装后的持久化reducer创建store export const store = createStore(persistedReducer); // 传入store实例创建persistor export const persistor = persistStore(store);
App.js入口文件
import React, { Component } from 'react' import { StyleSheet } from 'react-native' import Router from './router'; import { PersistGate } from 'redux-persist/integration/react'; import { Provider } from 'react-redux'; // 修正导入命名,和导出的小写store保持一致 import { store, persistor } from './redux/store/index'; export default class App extends Component { render() { return ( <Provider store={store}> <PersistGate persistor={persistor} loading={null}> <Router/> </PersistGate> </Provider> ) } } const styles = StyleSheet.create({})
额外注意事项
- JS变量大小写敏感,导入导出时要保持命名完全一致,否则会拿到undefined触发各类报错
- 所有Redux reducer必须补全default分支返回当前state,否则初始化、触发未知action时会出现状态异常
- 传入persistReducer、createStore的reducer只需要传函数引用,不要加括号手动执行,Redux内部会在需要时自动调用reducer
内容的提问来源于stack exchange,提问作者hafidh
相关产品推荐
相关产品推荐

