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))
})
}
}
为此,请指导我。
谢谢
答案 0 :(得分:1)
Redux是一个以反应方式工作的库,因此它等待调度动作以将状态更改散布到所有连接的函数中。
如果您设置了5秒的超时时间来分派操作,那么对于Redux来说,这与您在现实生活中等待5秒然后致电dispatch()
相同。它将通过更新所有连接的功能来响应该动作。
您的问题更多是关于承诺的。
在此期间,fetchedUser是否有可能尚未更新 执行dispatch(getUser(userId))。然后?
否,因为您在getUser操作之后使用.then
,并且这确保了fetchUser承诺已得到解决。可能发生的事情是找不到用户或类似的东西,但是在该代码块中,您可以确保fetchUser调用已完成。
流程如下:
fetchedUser = getState().usersById[userId]
如果我写setTimeout(()=> {dispatch({类型: 'fetchUser.then中的'GET_USER_SUCCESS',id,response})},5000)
在这种情况下,它可以在不更新状态的情况下运行fetchedUser分配行,因为我假设设置用户的是GET_USER_SUCCESS
操作,对吗?因此,如果请求完成时间少于5秒,它将在使用用户数据更新状态之前运行分配。