首页 > 解决方案 > 如果我的动作创建者返回承诺,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))
    })
  } 
}

请指导我。

谢谢

标签: javascriptreduxredux-thunk

解决方案


Redux 是一个以响应式方式工作的库,因此它等待分派操作以将状态更改传播到所有连接的函数。

如果你设置一个 5 秒的超时时间来调度一个动作,对于 Redux 来说就像你在现实生活中等待 5 秒然后调用dispatch(). 它只会通过更新所有连接的功能来响应该操作。

您的问题更多关于承诺。

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

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

流程是这样的:

  1. 调用 getUser(userId)
  2. 调度 GET_USER_REQUEST
  3. 调用 fetchUser()
  4. 等到 fetchUser 完成。
  5. 派遣 GET_USER_SUCCESS
  6. fetchedUser = getState().usersById[userId]
  7. 等等..

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

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


推荐阅读