我如何使用 Redux API 中间件和 Thunk 来链接 API 请求
How do I use Redux API Middleware and Thunk to chain API requests
我有几个像这样的 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
的第三个操作吗?但是那会是什么样子呢?
使用 redux-thunk
并创建名为 getUserThenPosts
的第三个操作。
export const getUserThenPosts = id => dispatch => {
return dispatch(getUserById(id))
.then((payload) => {
return dispatch(getUserPosts(payload.someIdFromUserPayload)));
};
};
我假设 getUserPosts
需要来自 user
有效负载的参数。
我有几个像这样的 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
的第三个操作吗?但是那会是什么样子呢?
使用 redux-thunk
并创建名为 getUserThenPosts
的第三个操作。
export const getUserThenPosts = id => dispatch => {
return dispatch(getUserById(id))
.then((payload) => {
return dispatch(getUserPosts(payload.someIdFromUserPayload)));
};
};
我假设 getUserPosts
需要来自 user
有效负载的参数。