如何使用Redux API中间件和Thunk链接API请求

时间:2018-08-13 18:45:11

标签: redux redux-thunk redux-api-middleware

我有几种类似的RSAA动作:

export const getUserById = id => ({
  [RSAA]: {
    endpoint: "...",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    types: [
      GET_USER_BY_ID_REQUEST,
      GET_USER_BY_ID_SUCCESS,
      GET_USER_BY_ID_FAILURE
    ]
  }
});

export const getUserPosts = id => ({
  [RSAA]: {
    endpoint: "...",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    types: [
      GET_USER_POSTS_REQUEST,
      GET_USER_POSTS_SUCCESS,
      GET_USER_POSTS_FAILURE
    ]
  }
});

要使用thunk(我认为)来链接这两个动作,我该怎么办?

我可以创建名为getUserThenPosts的第三个动作吗?但是那会是什么样?

1 个答案:

答案 0 :(得分:0)

使用redux-thunk并创建名为getUserThenPosts的第三个动作。

export const getUserThenPosts = id => dispatch => {
  return dispatch(getUserById(id))
    .then((payload) => {
      return dispatch(getUserPosts(payload.someIdFromUserPayload)));
    };
};

我假设getUserPosts需要来自user有效负载的参数。