2016-11-18 42 views
1

也許這已經回答過,但我很難找到答案。訪問狀態從另一個減速器反應/ Redux

我必須爲他們自己的初始狀態減速機。有沒有一種方法(當然是好的做法)從一個減速器訪問初始狀態?

減速機一:

const initialState = Immutable.fromJS({ loadData: [] }) 

const reducerOne = (state = initialState, action) => { 
    switch (action.type) { 
    case SELECT_REPORT_FORMAT: { 
     return state.merge({ loadData: state.get('loadData') }); 
    } 
    .... 
} 

減速二:

const initialState = Immutable.fromJS({ newData: [] }); 
const reducerTwo = (state = initialState, action) => { 
    switch (action.type) { 
    case GET_NEW_DATA: { 
     // Is there a way to "call" the SELECT_REPORT_FORMAT in 
     // reducerOne and get its new state (state.get('loadData')) from here? 
     // I did add case SELECT_REPORT_FORMAT in this reducer, and 
     // it did get called, but the state is with the property of 
     // newData, which makes sense. I need to access the loadData 
     // array from here. 
     return state.merge({ newData: state.get('loadData') }); 
    } 
    .... 
} 

謝謝!

回答

0

我沒有看到出口initialState並在需要的地方導入它的危害!

所以只需添加export const initialState = yourStuff,然後從您的其他減速器導入它。

+0

感謝您的響應,但我需要從減速器之一中的「SELECT_REPORT_FORMAT」調用後獲得初始狀態的最終結果。 – FNMT8L9IN82

+0

我的意思是我需要state.merge({loadData:state.get('loadData')})在reducer二內的返回值。 – FNMT8L9IN82

+0

好吧,不是初始狀態,你打算在一些行動被解僱後說出狀態。在這種情況下,不,你不應該達到其他減速器的狀態,因爲這會破壞封裝並可能導致無限循環。爲什麼不讓組件觸發ReducerA用於響應ReducerB引起的狀態變化的動作? – ZekeDroid

0

首先,

return state.merge({ loadData: state.get('loadData') }); 

沒有意義真的。但無論如何,我會建議爲initialState使用相同的值。這意味着你現在擁有的方式很好 - 對於兩個reducers,loadData和newData將分別爲空數組。

之後,當您使用type: GET_DATApayload: {data: 'blahBlah'}調用actionCreator時,您所要做的就是從兩個縮減器中獲取此操作。

const initialState = Immutable.fromJS({ loadData: [] }) 
const reducerOne = (state = initialState, action) => { 
    switch (action.type) { 
    case GET_DATA: { 
     return state.merge(fromJS({ loadData: action.payload.data) })); 
    } 
    .... 
} 

const initialState = Immutable.fromJS({ newData: [] }); 
const reducerTwo = (state = initialState, action) => { 
    switch (action.type) { 
    case GET_DATA: { 
     return state.merge(fromJS({ newData: action.payload.data) })); 
    } 
    .... 
} 

action.payload.dataloadData你想在你的問題就搞定了。希望它有助於:)

相關問題