与Redux Thunk结合使用时,Redux保持不持久状态

问题描述 投票:0回答:1

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

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 };
};

Store / 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;

Store / 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个回答
0
投票

我已解决您的问题,请通过fiverr与我联系

© www.soinside.com 2019 - 2024. All rights reserved.