设想
有 2 个 api 调用
- 请求 A(call) 获取 userId
- 使用 userId 请求 B(调用)(例如 /${userId}/detail)
并且响应数据将保存在 redux 存储中
- 如果 userId 已经作为全局状态存在,您可以使用该值发出 B 请求。
- 如果userId作为全局状态不存在,则在请求B之前请求A,然后在将userId添加到全局状态时请求B(必须同步操作)
我尝试了以下方法:
- 使用承诺。在这里,我们不检查 userId 是否存在于 store 中。这不是首选,因为即使存储中存在 userId,它也会无条件地请求两次。
export const getUserDetailData = createAsyncThunk(
'user/detail',
(url: string, { getState, dispatch }) => {
dispatch(getUserData())
.then((user)=> client.get(`/${user.id}/${url}`))
.then(res=>res)
}
);
- 这是使用 redux-thunk 提供的 function(getState) 的方法。
export const getUserDetailData = createAsyncThunk(
'user/detail',
async (url: string, { getState, dispatch }) => {
// "getState()" method to check if the desired data is present
if (!(getState() as RootState).user.data) {
// If there is no userId, a request is made to get the user's id.
await dispatch(getUserData());
}
// Get the value of the global store again and use userId
const userId = (getState() as RootState).user.data
const response = await client.get<APIData<any>>(`/${userId}/${url}`);
return response;
}
);
问题
我想知道的是,
对于案例 2,是否有一种比每次都调用并使用实时存储值与 getState 更具 thunk 风格的方法?