React Native集成redux-persist报config.storage is required错误排查
问题根因
报错触发原因是redux-persist配置项属性名拼写错误:配置对象要求传入全小写开头的storage字段指定存储引擎,你的代码里写的是大写开头的Storage,框架读取不到必填的storage配置,直接抛出参数缺失错误。
除此之外代码还有三处隐藏问题,不修复会触发后续运行报错:
- 已引入
redux-thunk但创建store时未通过applyMiddleware挂载,后续异步action会执行失败 - store文件用默认导出(
export default)包裹创建函数,App.js却用命名导入的方式引入,会报模块不存在错误 - 每次App组件渲染都会重新执行store创建函数,会导致状态丢失、重复订阅等异常
修复方案
1. 重写store配置文件
修正属性名拼写,补上中间件挂载,直接导出全局唯一的store、persistor实例,避免重复创建:
import {applyMiddleware, createStore} from "redux"; import thunk from "redux-thunk"; import rootReducer from "./reducer/index"; import AsyncStorage from "@react-native-async-storage/async-storage"; import {persistReducer,persistStore} from "redux-persist"; const persistConfig = { key: 'root', storage: AsyncStorage, // 修正为小写开头的storage // 可选:配置白名单指定需要持久化的reducer,减少存储占用 // whitelist: ['reducer'] }; const persistedReducer = persistReducer(persistConfig, rootReducer) export const store = createStore(persistedReducer, applyMiddleware(thunk)) export const persistor = persistStore(store)
2. 修正App.js的导入逻辑
去掉函数调用创建store的写法,直接导入全局唯一的store、persistor实例:
import React from 'react'; import { Text, View, Button, StyleSheet } from 'react-native'; import { useDispatch, useSelector } from "react-redux" import { Provider } from 'react-redux'; import {numIncrement} from './reduxConfig/Action' import { PersistGate } from 'redux-persist/es/integration/react'; // 修正导入方式 import { store, persistor } from './reduxConfig/store'; const Root = () => { const dispatch = useDispatch(); const txt = useSelector(state => state.reducer.count); return( <View> <Text style={styles.txxt}>{txt}</Text> <View style={styles.btn}> <Button title='counter' onPress={()=>dispatch(numIncrement())}/> </View> </View> ) } const App = () => { return ( <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <Root/> </PersistGate> </Provider> ); }; const styles = StyleSheet.create({ txxt:{ fontSize:100, color:"black" }, btn:{ top:200 } }) export default App;
注意事项
React Native环境不要直接导入web端默认存储redux-persist/lib/storage,该适配基于浏览器localStorage实现,RN环境无法运行,必须使用@react-native-async-storage/async-storage作为存储引擎。
改完后重新metro构建、重启应用即可实现计数状态的持久化留存。
内容的提问来源于stack exchange,提问作者Anuj
相关产品推荐
相关产品推荐

