如果我的动作创建者返回诺言,Redux何时解析调度?

问题描述 投票:0回答:1

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))
    })
  } 
}
javascript redux redux-thunk
1个回答
0
投票

允许您使用诺言的是Redux-thunk中间件。

Redux是一个以响应方式工作的库,因此它等待调度动作以将状态更改散布到所有连接的函数。

如果您设置5秒的超时时间来分派操作,那么对于Redux,这与您在现实生活中等待5秒然后调用dispatch()相同。它将通过更新所有连接的功能来响应该操作。

您的问题更多是关于诺言。

是否有可能fetchedUser在此期间尚未更新执行dispatch(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. 依此类推..
© www.soinside.com 2019 - 2024. All rights reserved.