簡體   English   中英

如果我的操作創建者返回 promise,Redux 何時解決調度?

[英]When does Redux resolve a dispatch if my action creator return promise?

在這篇文章中,Dan 編寫了一個片段來演示異步操作。

我想知道Redux如何知道我的store已完全更新?

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

如果我在 fetchUser.then 中寫 setTimeout(()=>{ dispatch({ type: ' fetchUser.then setTimeout(()=>{ dispatch({ type: 'GET_USER_SUCCESS', id, response }) }, 5000)會發生什么?

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 是一個以反應方式工作的庫,因此它等待調度操作以將 state 更改傳播到所有連接的函數。

如果你設置一個 5 秒的超時來調度一個動作,對於 Redux 這就像你在現實生活中等待 5 秒然后調用dispatch()一樣。 它只會通過更新所有連接的功能來響應該操作。

您的問題更多關於承諾。

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

不,因為您在 getUser 操作之后使用.then ,這是確保 fetchUser promise 已經解決。 可能發生的情況是找不到用戶或類似的情況,但在該塊中,您可以確保 fetchUser 調用已經完成。

流程將像這樣 go :

  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) 會發生什么

在這種情況下,它可以在不更新 state 的情況下運行 fetchedUser 分配行,因為我假設設置用戶的是GET_USER_SUCCESS操作,對吧? 因此,如果請求完成時間少於 5 秒,它將在使用用戶數據更新 state 之前運行分配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM