如果我的动作创建者返回承诺,Redux什么时候解决调度问题



在这篇文章中,Dan写了一个片段来演示异步操作。

我想知道Redux是如何知道我的store已经完全更新的?

在执行dispatch(getUser(userId)).then期间,是否存在fetchedUser尚未更新的可能性?

如果我写会发生什么fetchUser.then中的setTimeout(()=>{ dispatch({ type: 'GET_USER_SUCCESS', id, response }) }, 5000)

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()是一样的。它将通过更新所有连接的函数来响应该操作。

您的问题更多的是关于承诺

fetchedUser是否有可能在正在执行调度(getUser(userId((。那么?

否,因为您在getUser操作之后使用.then,这是为了确保fetchUser承诺已经得到解决。可能发生的情况是找不到用户或类似的情况,但在该块中,您可以确保fetchUser调用已经完成。

流程如下:

  1. 调用getUser(userId(
  2. 调度GET_USER_REQUEST
  3. 调用fetchUser((
  4. 等待fetchUser完成
  5. 调度GET_USER_SUCCESS
  6. 运行fetchedUser = getState().usersById[userId]
  7. 等等

如果我写setTimeout(((=>{dispatch({type:fetchUser.then 中的'GET_USER_SUCCESS',id,response}(},5000(

在这种情况下,它可以在不更新状态的情况下运行fetchedUser赋值行,因为我假设设置用户的是GET_USER_SUCCESS操作,对吧?因此,如果请求的完成时间不到5秒,它将在使用用户数据更新状态之前运行分配。

最新更新