从另一个Reducer React / Redux访问状态

时间:2016-11-18 23:00:17

标签: reactjs redux state reducers

以前可能已经回答了这个问题,但我很难找到答案。

我必须使用自己的初始状态减速器。有没有办法(当然是好的做法)从一个减速器访问初始状态?

Reducer One:

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') });
    }
    ....
}

谢谢!

2 个答案:

答案 0 :(得分:0)

我没有看到导出initialState并在需要时导入它的危害!

所以只需添加export const initialState = yourStuff,然后从其他reducer中导入它。

答案 1 :(得分:0)

首先,

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

真的没有意义。但无论如何,我建议对initialState使用相同的值。这意味着你现在拥有它的方式很好 - 对于reducers来说,loadData和newData分别是空数组。

之后,当使用type: GET_DATApayload: {data: 'blahBlah'}调用actionCreator时,您所要做的就是从两个reducer中获取此操作。

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,您试图提出问题。希望它有所帮助:)