2016-11-30 87 views
2

我試圖使用redux-persist來保存數據。這裏是我的代碼:asyncLocalStorage需要一個全局localStorage對象

import { createStore as _createStore, applyMiddleware, compose } from 'redux'; 
import createMiddleware from './middleware/clientMiddleware'; 
import { routerMiddleware } from 'react-router-redux'; 
import {persistStore, autoRehydrate} from 'redux-persist'; 

export default function createStore(history, client, data) { 
    // Sync dispatched route actions to the history 
    const reduxRouterMiddleware = routerMiddleware(history); 

    const middleware = [createMiddleware(client), reduxRouterMiddleware]; 

    let finalCreateStore; 
    if (__DEVELOPMENT__ && __CLIENT__ && __DEVTOOLS__) { 
    const { persistState } = require('redux-devtools'); 
    const DevTools = require('../containers/DevTools/DevTools'); 
    finalCreateStore = compose(
     applyMiddleware(...middleware), 
     window.devToolsExtension ? window.devToolsExtension() : DevTools.instrument(), 
     persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) 
    )(_createStore); 
    } else { 
    finalCreateStore = applyMiddleware(...middleware)(_createStore); 
    } 

    const reducer = require('./modules/reducer'); 
    // const store = finalCreateStore(reducer, data); 
    const store = finalCreateStore(reducer, data, autoRehydrate()); 
    if (typeof window !== 'undefined') persistStore(store); 

    if (__DEVELOPMENT__ && module.hot) { 
    module.hot.accept('./modules/reducer',() => { 
     store.replaceReducer(require('./modules/reducer')); 
    }); 
    } 

    return store; 
} 

它適用於單一流程。但是,如果我刷新除homePage以外的任何頁面的頁面,則頁面上的所有內容都會干擾。我也收到以下警告:

[1] redux-persist asyncLocalStorage requires a global localStorage object. Either use a different storage backend or if this is a universal redux application you probably should conditionally persist like so: https://gist.github.com/rt2zz/ac9eb396793f95ff3c3b 
[1] Warning: React can't find the root component node for data-reactid value `.15mzo5h179c.3.0.0`. If you're seeing this message, it probably means that you've loaded two copies of React on the page. At this time, only a single copy of React can be loaded at a time. 

P.我正在使用react-redux-universal-hot-example樣板文件

+0

'localStorage'只存在於瀏覽器上。 – lux

回答

2

只有當您在客戶端上運行時,纔想使用localStorage存儲增強器有條件地創建商店。

... 
const reducer = require('./modules/reducer'); 
let store; 

if (__CLIENT__) { 
    store = finalCreateStore(reducer, data, autoRehydrate()); 
    persistStore(store); 
} else { 
    store = finalCreateStore(reducer, data); 
} 
... 
+0

我試過但沒有工作。 –

+0

也許試試,「if(typeof window!=='undefined')persistStore(store);」 –

+0

仍然是同樣的問題?我應該分享完整的redux創建模塊嗎? –