例如:我希望當反應應用程序被打開時,它將創建一個key爲「user」的redux樹,並且值是用戶對象從LocalStorage進行解析(當用戶被登錄)。Redux:我們應該在哪裏爲初始化狀態設置反應應用程序
我想我應該把createStore
。這是我創建存儲代碼:
import { applyMiddleware, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import makeRootReducer from './reducers';
import { updateLocation } from './location';
export default (initialState = {}) => {
const middleware = [thunk];
const enhancers = [];
let composeEnhancers = compose;
const store = createStore(
makeRootReducer(),
initialState,
composeEnhancers(applyMiddleware(...middleware), ...enhancers)
);
window.store = store;
store.asyncReducers = {};
store.unsubscribeHistory = browserHistory.listen(updateLocation(store));
// const history = syncHistoryWithStore(browserHistory, store);
// console.log(history);
return { store: store, history: null };
};
因此,作爲權作爲存儲中創建,我初始化對象:
const store = createStore(
makeRootReducer(),
initialState,
composeEnhancers(applyMiddleware(...middleware), ...enhancers)
);
store.getState().sampleString = "StackOverFlow";
但是,當我反應過來的應用程序開始時,我沒有看到「sampleString」鍵在這個redux樹。請幫我弄清楚哪一部分是我錯了。
感謝
你必須派一些行動改變狀態。我認爲這是觸發狀態更改的唯一方法 –
其中定義了傳遞給該函數的initialState?該變量應該保留你的密鑰。如果你想讓它成爲最初的狀態,你不應該改變狀態。 – lilezek
@EQuimper能否解釋爲什麼減持可以解決我的問題的更多細節。正如我所知,redux-persist幫助我們將redux樹保存到本地存儲。 –