javascript - 如果我的动作创建者返回承诺,Redux 什么时候解决调度?
问题描述
在这篇文章中,Dan 编写了一个片段来演示异步操作。
我想知道如何Redux
知道我store
的已完全更新?
执行期间是否有机会fetchedUser
尚未更新dispatch(getUser(userId)).then
?
如果我写
setTimeout(()=>{ dispatch({ type: 'GET_USER_SUCCESS', id, response }) }, 5000)
进去会怎样fetchUser.then
?
export function getUser(id) {
return dispatch => {
dispatch({ type: 'GET_USER_REQUEST', id })
// Perform the actual API call
return fetchUser().then(
response => {
// Reducers may handle this to show the data and reset isFetching
dispatch({ type: 'GET_USER_SUCCESS', id, response })
},
error => { ... }
)
}
}
export function getUserAndTheirFirstPost(userId) {
return (dispatch, getState) => {
return dispatch(getUser(userId)).then(() => {
// Assuming this is where the fetched user got stored
const fetchedUser = getState().usersById[userId]
// Assuming it has a "postIDs" field:
const firstPostID = fetchedUser.postIDs[0]
return dispatch(getPost(firstPostID))
})
}
}
请指导我。
谢谢
解决方案
Redux 是一个以响应式方式工作的库,因此它等待分派操作以将状态更改传播到所有连接的函数。
如果你设置一个 5 秒的超时时间来调度一个动作,对于 Redux 来说就像你在现实生活中等待 5 秒然后调用dispatch()
. 它只会通过更新所有连接的功能来响应该操作。
您的问题更多关于承诺。
在执行 dispatch(getUser(userId)).then 期间是否有可能 fetchedUser 尚未更新?
不,因为您在.then
getUser 操作之后使用,这是确保 fetchUser 承诺已经解决。可能发生的情况是找不到用户或类似的情况,但在该块中,您可以确保 fetchUser 调用已经完成。
流程是这样的:
- 调用 getUser(userId)
- 调度 GET_USER_REQUEST
- 调用 fetchUser()
- 等到 fetchUser 完成。
- 派遣 GET_USER_SUCCESS
- 跑
fetchedUser = getState().usersById[userId]
- 等等..
如果我在 fetchUser.then 中写 setTimeout(()=>{ dispatch({ type: 'GET_USER_SUCCESS', id, response }) }, 5000) 会发生什么
在这种情况下,它可以在不更新状态的情况下运行 fetchedUser 分配行,因为我假设设置用户的是GET_USER_SUCCESS
操作,对吧?因此,如果请求完成时间少于 5 秒,它将在使用用户数据更新状态之前运行分配。
推荐阅读
- java - java - 如何将textview中脚本bash的输出显示为java中的列表?
- python - 有没有一种简单的方法可以使用 python 从网站上刮掉一张桌子(按下按钮后)?
- c - 我可以使用“MAX”宏来检查是否所有位都已设置?
- c++ - 头文件 (C++) 中的更改会被忽略吗?
- python - 用破折号下拉过滤 pd.DataFrame
- swift - SwiftUI/UIKit Introspection 在 iOS 14 上被破坏
- node.js - DocuSign 获取 JWT 令牌 MEAN Stack
- python - 如何为python脚本制作别名,类似于黑色?
- javascript - 如何将 Vue 组件构建为支持 SSR 的 Nuxtjs 库?
- c++ - C++ 入门 TextQuery 程序