簡體   English   中英

React redux 如何使用 getState()

[英]React redux how to use getState()

我正在從Firebase Real-time database獲取數據並將其存儲到我的 redux 狀態中。 如何創建一個在初始調用后獲得最新狀態的操作?

const getIds = (state) => state.notes.activeNotes;

export const getUserNotes = (currentUserId) => (dispatch, getState) => {
  getFromFirebase(`/Notes/${currentUserId}/`, (response) => {
    var ids = Object.keys(response)
      dispatch(setNoteIds(ids)); //should dispatch ids something like this [1,2,3,4,5]
  })

  const test= getIds(getState());
  console.log(test); //current output []
}

Expected output: [1,2,3,4,5]
Actual output: []

假設函數getFromFirebase返回一個承諾,那么您可以將方法切換為異步,如下所示:


export const getUserNotes = (currentUserId) => async (dispatch, getState) => {
  // wait the result dispatched
  await getFromFirebase(`/Notes/${currentUserId}/`, (response) => {
    var ids = Object.keys(response)
      dispatch(setNoteIds(ids)); //should dispatch ids something like this [1,2,3,4,5]
  })
  
  const test= getIds(getState());
}

或者,如果getFromFirebase不是承諾,您可以通過承諾將其包裝起來:

export const getUserNotes = (currentUserId) => async (dispatch, getState) => {
  // wrap in a promise
  await new Promise(resolve => {
    getFromFirebase(`/Notes/${currentUserId}/`, (response) => {
      var ids = Object.keys(response)
        dispatch(setNoteIds(ids)); //should dispatch ids something like this [1,2,3,4,5]
        resolve();
    })
  })
  
  const test= getIds(getState())
}

暫無
暫無

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

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