【问题标题】:React Native Redux Persist not persisting state when combined with Redux Thunk与 Redux Thunk 结合使用时,React Native Redux Persist 不持久化状态
【发布时间】:2026-02-12 12:40:02
【问题描述】:

我正在构建一个 React Native 应用程序并且我正在使用 Redux。 Redux Persist 工作正常,但是当我添加 Redux Thunk 时,商店的状态没有持久化。 state.test 变量的值确实更改为从 api 获取的值,但是当我重新启动应用程序时,该值再次等于初始值。我创建了一个简单的示例来重现此行为。该示例由 5 个文件组成,我还使用示例代码 https://github.com/JenteBeerten/reduxPersistProblem 创建了一个 git 存储库

Store/Actions/test.js

export const SET_TEST = 'SET_TEST';

export const fetchTest = () => {
    return async dispatch => {
        fetch('http://dummy.restapiexample.com/api/v1/employee/1',{
            method: 'GET',
            headers: {
            'Content-Type': 'application/json',
            },
            }).then((response) => response.json())
            .then((json) => {
                dispatch({
                    type: SET_TEST, test: json.data.employee_name
                });
            })
            .catch((error) => {
                console.error(error);
            });
    }
};

export const setTest = (test) => {
    return { type: SET_TEST, test: test };
};

存储/reducers/test.js

import { SET_TEST } from "../actions/test";

const initialState = {
    test: 'testInitialValue'
}

const testReducer = (state = initialState, action) => {
    switch (action.type) {
        case SET_TEST:
            state.test = action.test;
            return state;
        default: 
            return state;
    }
}

export default testReducer;

存储/configureStore.js

import { createStore, combineReducers, applyMiddleware } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import AsyncStorage from '@react-native-community/async-storage';
import ReduxThunk from 'redux-thunk';
import testReducer from './reducers/test';

const rootReducer = combineReducers({
  test: testReducer
});

const persistConfig = {
  key: 'root',
  storage: AsyncStorage
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export default () => {
  let store = createStore(
    persistedReducer,
    applyMiddleware(ReduxThunk)
  );
  let persistor = persistStore(store)

  return { store, persistor }
}

App.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';

import returnStoreAndPersistor from './store/configureStore';
import TestComponent from './TestComponent';
const {store, persistor} = returnStoreAndPersistor();

export default function App() {


  return (
  <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <View style={styles.container}>
          <TestComponent></TestComponent>
        </View>
      </PersistGate>
  </Provider>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

TestComponent.js

import React, { useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';

import { useSelector, useDispatch } from 'react-redux';
import * as testActions from './store/actions/test';

const TestComponent = props => {
  const dispatch = useDispatch();

  var test = useSelector(state => state.test.test);
  console.log('test='+test);

  useEffect(() => {

      dispatch(testActions.fetchTest());
    }, [dispatch]);

    return (
    <View style={styles.container}>
      <Text> Test is {test} </Text>
    </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
      }
  });


export default TestComponent;

【问题讨论】:

    标签: reactjs redux native persist thunk


    【解决方案1】:

    在 reducer 中,您必须将先前状态的副本返回为

    import { SET_TEST } from "../actions/test";
    
    const initialState = {
        test: 'testInitialValue'
    }
    
    const testReducer = (state = initialState, action) => {
        switch (action.type) {
            case SET_TEST:
                return {
                 ...state,
                test: action.test;
                }
            default: 
                return state;
        }
    }
    
    export default testReducer;
    

    现在它将持续存在。

    谢谢

    【讨论】:

    • 这是 reducer 的默认实现。此 sn-p 与持久数据无关