是否有必要在redux-persist中实施REHYDRATE案例?

时间:2018-12-24 15:30:26

标签: redux redux-persist

我正在使用react-native进行概念验证,并且正在使用redux-persist。根据我所读的内容,状态在版本5中会自动分配,但是没有REHYDRATE情况,我就无法为状态补水。

我的减速器:

import {ADD_USER} from '../constants/actionTypes';
import { REHYDRATE } from 'redux-persist';


const initialState = {
    userName: null,
    fetching: false
};

const userReducer = (state = initialState, action) => {
    let copied = Object.assign({}, state);
    switch (action.type){
        case ADD_USER:
            copied.userName = action.payload;
            break;
        case REHYDRATE:
            //console.log('Payload desde el reducer ', action.payload);fsdffdsdsfsdfsdf
            copied = action.payload.userReducer;
            break;
        default:
            break;
    }

    return copied;
};

export default userReducer;

我的configureStore

const persistConfig = {
    key: 'root',
    storage,
    stateReconciler: autoMergeLevel2,
};

function logger({ getState }) {
    return (next) => (action) => {
        let returnValue = next(action)
        return returnValue
    }
}

const persistedReducer = persistCombineReducers(persistConfig, {userReducer});

export default () => {
    let store = createStore(persistedReducer, undefined, applyMiddleware(logger));
    let persistor = persistStore(store, null, () => {
        Alert.alert(
            'Fucking state',
            JSON.stringify(store.getState()),
            [
                {text: 'OK', onPress: () => console.log('OK Pressed')},
            ],
            { cancelable: false }
        );
    });
    return { store, persistor }
}

1 个答案:

答案 0 :(得分:1)

我的问题是我在方法末尾返回了状态,而不是在每次切换时都返回了状态,这肯定会破坏自动补液。更换减速器使我的问题消失了。

reducer代码如下:

const initialState = {
    userName: null,
    fetching: false
};

const userReducer = (state = initialState, action) => {
    switch (action.type){
        case ADD_USER:{
            let copied = Object.assign({}, state);
            copied.userName = action.payload;
            return copied;
        }
        default:
            return state;
    }
};

export default userReducer;