使用 Redux 和 React 按顺序执行异步操作
Executing async actions in order with Redux and React
在我的 React/Redux 应用程序中,我有自定义 group
对象。我想要一个页面,显示所有组的摘要列表以及当前所选组的详细视图(默认为列表中的第一个组)。我需要从我的休息 api 请求组列表 (/groups
),获取第一组的 id
(从商店?)并将其设置为 selected group
,然后向 return 所选组 (/groups/${id}/members
)
的成员列表发出 get
请求
我是 React/Redux 的新手,我不确定如何编写代码。我应该把它写成 3 个单独的动作吗?我可以使用前一个动作的结果让反应组件调用这些动作吗?或者我应该使用 thunk 中间件将此逻辑放在组合操作处理程序中吗?在那种情况下我将如何编写这样的动作处理程序?
最好编写 3 个动作,然后使用 thunk 将它们链接在一起。此外,任何请求都是异步的,因此无论如何它们都需要使用 thunk 或其他一些异步方法。所以对 /groups
和 /groups/${id}/members
的请求将是看起来像这样的 thunks(箭头功能只是为了简洁):
export const requestGroups = () => (
(dispatch) => {
// Maybe dispatch an action here that says groups are loading,
// for showing a loading icon or something
return fetch('/groups').then((response) => (
dispatch(updateGroups(response))
// Or just dispatch({ type: 'UPDATE_GROUPS', groups: response })
)
}
)
其中 updateGroups
是将响应数据发送到 reducer 以使其进入状态的操作。并确保这些 thunk return promises 以便您稍后可以将它们链接在一起。您可能还想在这里进行一些错误处理。
然后一旦你完成了这三个动作,你就可以制作一个将它们组合在一起的 thunk:
export const initializeGroups = () => (
(dispatch, getState) => (
dispatch(loadGroups()).then(() => {
const { groups } = getState(); // Or wherever the list is
setSelectedGroup(groups[0]);
return getGroupData(groups[0]);
}).then(() => {
// Dispatch an action saying everything is done, or do any other stuff here.
}).catch((error) => {
// Do any error handling
});
)
)
在我的 React/Redux 应用程序中,我有自定义 group
对象。我想要一个页面,显示所有组的摘要列表以及当前所选组的详细视图(默认为列表中的第一个组)。我需要从我的休息 api 请求组列表 (/groups
),获取第一组的 id
(从商店?)并将其设置为 selected group
,然后向 return 所选组 (/groups/${id}/members
)
get
请求
我是 React/Redux 的新手,我不确定如何编写代码。我应该把它写成 3 个单独的动作吗?我可以使用前一个动作的结果让反应组件调用这些动作吗?或者我应该使用 thunk 中间件将此逻辑放在组合操作处理程序中吗?在那种情况下我将如何编写这样的动作处理程序?
最好编写 3 个动作,然后使用 thunk 将它们链接在一起。此外,任何请求都是异步的,因此无论如何它们都需要使用 thunk 或其他一些异步方法。所以对 /groups
和 /groups/${id}/members
的请求将是看起来像这样的 thunks(箭头功能只是为了简洁):
export const requestGroups = () => (
(dispatch) => {
// Maybe dispatch an action here that says groups are loading,
// for showing a loading icon or something
return fetch('/groups').then((response) => (
dispatch(updateGroups(response))
// Or just dispatch({ type: 'UPDATE_GROUPS', groups: response })
)
}
)
其中 updateGroups
是将响应数据发送到 reducer 以使其进入状态的操作。并确保这些 thunk return promises 以便您稍后可以将它们链接在一起。您可能还想在这里进行一些错误处理。
然后一旦你完成了这三个动作,你就可以制作一个将它们组合在一起的 thunk:
export const initializeGroups = () => (
(dispatch, getState) => (
dispatch(loadGroups()).then(() => {
const { groups } = getState(); // Or wherever the list is
setSelectedGroup(groups[0]);
return getGroupData(groups[0]);
}).then(() => {
// Dispatch an action saying everything is done, or do any other stuff here.
}).catch((error) => {
// Do any error handling
});
)
)