Redux Sagas,多次并行执行同一操作

时间:2019-05-24 01:03:01

标签: redux react-redux

我如何并行put多次并行执行相同的操作类型,并且能够take进行所有响应?在Redux的文档中,它们使用callall并行进行API调用,但据我所读,仅在分派动作时才调用reducers。我该如何并行调度同一动作,获取每个动作的结果,并调用reducer?

# api/actions.ts
const getUserRequest = createAction('GET_USER_REQUEST', { userId });
const getUserSuccess = createAction('GET_USER_SUCCESS', { user });

# api/sagas.ts
function* fetchUser(action) {
  const user = axios.get(`api.example.com/users/${action.payload.userId}`;
  yield put({type: GET_USER_SUCCESS, user.data});
}

# api/reducers.ts
function (state, action) {
  switch(action.type) {
    case: GET_USER_REQUEST:
      return {
        ...state,
        [action.payload.userId] = {}
      };
    case: GET_USER_SUCCESS:
      return {
        ...state,
        [action.payload.userId] = {...action.payload}
      };
    default:
      return state;
  }
}

# ui/sagas.ts
function* fetchSelectedUsers(userIds: number[]){
  # I'm stuck at this saga.  How can I get multiple users, have reducers invoked, and perform additional processing in this saga after they've been retrieved?
  const actionsToDispatch = userIds.map(x =>
    put(getUserRequest({userId}))
  );

  yield all(actionsToDispatch);

  # Pseudo code
  const users = yield take(actionsToDispatch);
  users.map(x => {
    // Perform additional work from users that were returned.  Reducers must also be called from the `yield all(actionsToDispatch);` from above.
  });
}

0 个答案:

没有答案