2017-08-17 1 views
0

を反応させるために状態を初期化するに置く必要があります。キーは「ユーザー」があるとアプリが開かれた反応時に私が欲しいが、それは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」を参照してくださいしないでくださいこの還元木のキー。私が間違っていた部分を見つけ出すのを助けてください。

おかげ

+0

あなたが状態を変更するためのいくつかのアクションをディスパッチする必要があります。私は、それが状態変化をトリガーする唯一の方法だと思う。 –

+0

あなたはその関数に渡すinitialStateがどこに定義されていますか?その変数はあなたの鍵を保持しているはずです。状態を最初のものにしたい場合は、状態を変更するべきではありません。 – lilezek

+0

@EQuimperなぜredux-persistが私の問題を解決できるかについてもっと詳しく説明できますか?私が知っていたように、redux-persistは還元ツリーをローカルストレージに保存するのに役立ちます。 –

答えて

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

をそして、あなたははこの1つのようassignationsを使用して状態を変更することを避けなければならない:あなたはこのようなもので、それを呼び出すべきである

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

私は理解した。ここに私のコードです: 'const initialState = window .__ INITIAL_STATE__; const {store、customHistory} = createStore(initialState);私が 'const initialState = {sampleString:" StackOverFlow "}'を変更すると、 が呼び出されます。私はエラーに会う。 –

+0

エラーは次のとおりです。 "レデューサーが受け取った前の状態で見つかった予期しないキー" sampleString "。代わりに既知のレデューサーキーの1つが見つかりました:"場所 "。 –

+0

これを参照してください:https://stackoverflow.com/questions/37998281/react-redux-unexpected-key-passed-to-create-store。レデューサーでsampleStringキーが正しく定義されていません。 – lilezek

関連する問題