【问题标题】:React Redux thunk - render app after dispatches finishesReact Redux thunk - 调度完成后渲染应用程序
【发布时间】:2019-12-11 20:22:29
【问题描述】:

我的应用使用 React、Redux 和 Thunk。 我的应用呈现之前我希望将一些数据发送到商店。

如何确保ReactDOM.render() 所有调度完成后运行? 请参阅下面的代码

index.js

const setInitialStore = () => {
  return dispatch => Promise.all([
    dispatch(startSubscribeUser()),
    dispatch(startSubscribeNotes()),
  ]).then(() => {
    console.log('initialLoad DONE')
    return Promise.resolve(true)
  })
}

store.dispatch(setInitialStore()).then(()=>{
  console.log('Render App')
  ReactDOM.render(jsx, document.getElementById('app'))
})

动作

export const setUser = (user) => ({
  type: SET_USER,
  user
})
export const startSubscribeUser = () => {
  return (dispatch, getState) => {
    const uid = getState().auth.id

    database.ref(`users/${uid}`)
    .on('value', (snapshot) => {
      const data = snapshot.val()
      const user = {
        ...data
      }
      console.log('user.on()')
      dispatch(setUser(user))
    })
  }
}

export const setNote = (note) => ({
  type: SET_NOTE,
  note
})
export const startSubscribeNotes = () => {
  return (dispatch, getState) => {

    database.ref('notes')
    .on('value', (snapshot) => {
      const data = snapshot.val()
      const note = {
        ...data
      }
      console.log('note.on()')
      dispatch(setNote(note))
    })
  }
}

我的日志显示

"initialLoad DONE"
"Render App"
...
"user.on()"
"note.on()"

我期望user.on()note.on()initialLoad DONERender App 之前被记录

非常感谢! /K

【问题讨论】:

  • 其实我不明白为什么你的代码不能工作。
  • 也许你可以用dispatch做一个HOC,在你的store中找到需要的数据的条件下渲染子组件。
  • 感谢@EmmanuelMericdeBellefon!是的,我希望代码也能正常工作,但是日志记录表明我的操作在渲染之前没有完成。 :/ 我在帖子中添加了日志消息。
  • 好的,我想我明白了。

标签: reactjs firebase-realtime-database redux redux-thunk


【解决方案1】:

我很确定这是因为 startSubscribeUserstartSubscribeNotes 不返回返回承诺的函数

那么,在这种情况下会发生什么,database.ref 没有等待在执行下一个 then 之前完成。

我不确切知道 database 变量是什么,但这应该可以:

  return new Promise(resolve => {
    database.ref(`users/${uid}`)
    .on('value', (snapshot) => {
      const data = snapshot.val()
      const user = {
        ...data
      }
      console.log('user.on()')
      dispatch(setUser(user))
      resolve()
    })
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 2016-12-11
    • 2019-04-06
    • 2017-08-28
    • 1970-01-01
    • 2018-09-28
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多