英文:
Can we access the response of a request inside asyncThunk without selector and without passing by store or state in redux toolkit
问题
我想知道在redux toolkit中是否有可能在不经过store、state或selector的情况下访问asyncThunk的请求响应。有时候我们想要使用从一个请求接收到的数据来执行另一个请求。所以我们能否在不等待state或store更新,也不使用useEffect的情况下获取响应请求呢?
我的意思是在另一个请求中使用从asyncThunk接收到的响应,就像这样:
const {id} = await dispatch(getTest())
dispatch(getTestResultById(id))
英文:
I'm wondering if there is a possibility In redux toolkit to access request response of an asyncThunk without passing by store or state or selector.
Sometimes we wanna use the data received from a request to perform another request.
So can we get the response request without waiting for state or store to update and without using useEffect.
I mean using response received from the asyncThunk in another request something like that:
const {id} = await dispatch(getTest())
dispatch (getTestResultById(id))
答案1
得分: 1
是的,如果第一个操作是异步操作/异步函数,那么它可以被等待。Redux Toolkit的thunk始终会解析,所以请确保解开返回的解析后的Promise,以查看操作是否成功。
示例:
const handler = async () => {
try {
const { id } = await dispatch(getTest()).unwrap();
dispatch(getTestResultById(id));
} catch(error) {
// 处理被拒绝的Promise或任何抛出的异常
}
};
更多详细信息请参见处理Thunk结果。
英文:
Yes, if the first action is an asynchronous action/thunk then it can be awaited. Redux Toolkit thunks always resolve, so be sure to unwrap the returned resolved Promise to see if the action was successful or not.
Example:
const handler = async () => {
try {
const { id } = await dispatch(getTest()).unwrap();
dispatch (getTestResultById(id));
} catch(error) {
// handle rejected Promise or any thrown exceptions
}
};
For more details see Handling Thunk Results.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论