2017-08-17 61 views
0

例如:我希望當反應應用程序被打開時,它將創建一個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樹。請幫我弄清楚哪一部分是我錯了。

感謝

+0

你必須派一些行動改變狀態。我認爲這是觸發狀態更改的唯一方法 –

+0

其中定義了傳遞給該函數的initialState?該變量應該保留你的密鑰。如果你想讓它成爲最初的狀態,你不應該改變狀態。 – lilezek

+0

@EQuimper能否解釋爲什麼減持可以解決我的問題的更多細節。正如我所知,redux-persist幫助我們將redux樹保存到本地存儲。 –

回答

1

導出此函數:

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

讓調用該函數X。你應該像這樣來調用它:

X({sampleString: "StackOverflow"}); 

必須避免使用像幽會這一個改變狀態:

store.getState().sampleString = "StackOverFlow"; 
+0

謝謝。我明白了。這裏是我的代碼:'const initialState = window .__ INITIAL_STATE__; const {store,customHistory} = createStore(initialState); '當我改變'const initialState = {sampleString:「StackOverFlow」}''。我遇到錯誤。 –

+0

錯誤是:「異想要的鍵」sampleString「在減速器接收到的以前的狀態中找到。預期會找到一個已知的減速鍵而不是:」location「。意外的鍵將被忽略。 –

+0

請參閱:https://stackoverflow.com/questions/37998281/react-redux-unexpected-key-passed-to-create-store。您沒有在減速器中正確定義您的sampleString鍵。 – lilezek

相關問題