This post,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-thunk中间件。
Redux是一个以响应方式工作的库,因此它等待调度动作以将状态更改散布到所有连接的函数。
如果您设置5秒的超时时间来分派操作,那么对于Redux,这与您在现实生活中等待5秒然后调用dispatch()
相同。它将通过更新所有连接的功能来响应该操作。
您的问题更多是关于诺言。
是否有可能fetchedUser在此期间尚未更新执行dispatch(getUser(userId))。然后?
否,因为您要在getUser操作之后使用.then
,并且要确保fetchUser承诺已得到解决。可能发生的情况是找不到该用户或类似的东西,但是在该块中,您可以确保fetchUser调用已完成。
流程将像这样:
fetchedUser = getState().usersById[userId]