天天看点

我的React踩坑日记,持续更新。该博客会持续记录我的踩坑日记

该博客会持续记录我的踩坑日记

1、redux: createStore的preloadedState参数

    使用localStorage用作存储用户操作记录时,我们需要将将state转成json字符串存储在localStorage中。 同时我们需要在createStore中传入localStorage存储的state, 这时切记 切记一定要将json字符串转换成对象。否则会产生该异常:The preloadedState argument passed to createStore has unexpected type of “String”

import {createStore, combineReducers, applyMiddleware} from "redux";
import Reducers from "../reducers";

const saver = store => next => action => {
    next(action);
    localStorage['redux-cache'] = JSON.stringify(store.getState());
}

const storeFactory = () => {
    let cache = JSON.parse(localStorage['redux-cache']);
    return createStore(
        combineReducers({...Reducers}),
        cache ? cache : {},
        applyMiddleware(saver)
    )
}

export default storeFactory;