结合两个redux减速器

时间:2018-03-04 19:06:56

标签: redux react-redux

我有一个这样的用例:

eventListReducer:将根据日期范围获取事件列表

eventDetailReducer:将根据一个事件ID

获取事件详细信息

我知道怎么做以上两个,我的问题: 当我的页面最初加载时,我将根据默认日期范围获取事件列表并加载第一个事件详细信息,我当然可以创建一个 EventListAndDetailReducer复制eventListReducer和eventDetailReducer。有没有更好的方法可以重用逻辑?

我想要实现的是另一个操作,首先调用getEvents并更新eventLists状态,然后获取第一个事件并调用setEvent并更新eventDetail状态。

这是我的eventDetailReducer:

const initialState = {
    eventDetails: "",
}

const eventReducer = (state = initialState, action) => {
    switch (action.type) {
        case "SET_EVENT":
            state = {
                ...state,
                eventDetails: action.payload
        };

        break;
    }

    return state;
}

export default eventReducer; 

这是我的eventsReducer:

const initialState = {
    eventsList: [],
}

//getEventsReducer
const getEventsReducer = (state = initialState, action) => {
    switch (action.type) {
        case "GET_EVENTS":
            state = {
                ...state,
                eventList: ["Joe", "Tom", "Marry"] //assuming this from some other endpoint
            };
            break;
    }
    return state;
}

export default getEventsReducer; 

3 个答案:

答案 0 :(得分:0)

如何使用EventListAndDetailReducer

const initialState = {
  eventsList: [],
  eventDetails: ""
}

export function eventListAndDetailReducer(state, action) {
  switch(action.type) {
    case GET_EVENTS:
      return {...state, eventList: eventsReducer(state.eventsList, action)}
    case "SET_EVENT":
      return {...state, eventDetails: eventDetailsReducer(state.eventDetails, action)}
    default:
      return state
  }
}

然后有些人开始使用combineReducers

答案 1 :(得分:0)

为什么不让eventDetails缩减器更新GET_EVENTS动作?

const eventReducer = (state = initialState, action) => {
    switch (action.type) {
        case "SET_EVENT":
            state = {
                ...state,
                eventDetails: action.payload
        };
        break;
        case "GET_EVENTS":
            state = {
                ...state,
                eventDetails: action.payload[0] // assuming payload is an array
        };
        break;
    }

    return state;
}

请记住,所有reducer都接收所有操作,因此不需要进行1-1映射。

答案 2 :(得分:0)

我从你的问题中了解到,你想要另一个动作按顺序执行这两个动作并依赖于每个动作。我假设您有一些中间件,例如redux-thunk,它们允许操作不仅仅是plaIn函数!

export function combinedAction() {
 return (dispatch, getState) => {

  // Write fetch() request to get events list from anywhere.
  // Following should be within .then() if you're using fetch. 
  // Here events are just hardcoded in reducer! 

  dispatch(return { type: GET_EVENTS, payload: events }).then( () => {
     let event = getState().eventsList[0]
     dispatch(return { type: SET_EVENT, payload: event })
  })

 };
}

这将首先启动GET_EVENTS操作,并在state.eventsList中设置事件数组。然后,下一步操作只会使用此state信息来发送下一个操作SET_EVENT。请参阅此处以了解链接操作。 How to chain async actions?