Javascript 如果我的动作创建者返回承诺,Redux何时解决分派?
,Dan编写一个代码段来演示异步操作 我想知道Javascript 如果我的动作创建者返回承诺,Redux何时解决分派?,javascript,redux,redux-thunk,Javascript,Redux,Redux Thunk,,Dan编写一个代码段来演示异步操作 我想知道Redux如何知道我的store已完全更新 执行dispatch(getUser(userId)),是否有可能fetchedUser尚未更新。然后 export function getUser(id) { return dispatch => { dispatch({ type: 'GET_USER_REQUEST', id }) // Perform the actual API call return fet
Redux
如何知道我的store
已完全更新
执行dispatch(getUser(userId)),是否有可能fetchedUser
尚未更新。然后
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))
})
}
}
如果我写信会发生什么
setTimeout(()=>{dispatch({type:'GET_USER_SUCCESS',id,response}),5000)
在fetchUser中。然后
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操作之后使用
,这将确保已解决fetchUser承诺。可能发生的情况是找不到用户或类似的情况,但是在该块中,您可以确保fetchUser调用已经完成
流程如下所示:
调用getUser(用户ID)
调度获取用户请求
调用fetchUser()
等待fetchUser完成
调度获取用户成功
运行fetchedUser=getState().usersById[userId]
等等
如果我写入setTimeout(()=>{dispatch({type:
fetchUser.then中的'GET_USER_SUCCESS',id,response},5000)
在这种情况下,它可以在不更新状态的情况下运行fetchedUser分配行,因为我假设设置用户的是GET\u user\u SUCCESS
操作,对吗?因此,如果请求完成所需时间少于5秒,它将在使用用户数据更新状态之前运行分配。Hi,感谢您的回答,但我仍然很好奇dispatch(getUser(userId))
实际上返回了一个承诺,那么Redux何时解决这个承诺?Redux是否确保在解决此承诺之前更新存储
?@WilsonLiao调度
不关心该承诺。它只是通过getUser(userId)(dispatch)
返回的值。碰巧这个值是一个承诺,但对于redux
,它并不重要。从redux
的角度来看,这只是要传递的一些值。@wilsonlia如果您有redux承诺
并调用dispatch(somePromise)
,redux
将等待该承诺解析为某个操作,然后将该操作传递给rootReducer以获得新状态。但是您没有redux承诺
,也没有分派承诺,而是分派函数。在阅读redux源代码后,最终找到它。因为dispatch
函数返回action
,所以dispatch(getUser(userId))
实际上等于fetchUser()。然后
,所以它肯定在fetchUser()之后执行。然后
。非常感谢。