2016-11-18 137 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你想在你的问题就搞定了。希望它有助于:)

相关问题