【问题标题】:getIndexRoute after getComponent is all completedgetComponent 全部完成后的 getIndexRoute
【发布时间】:2016-06-28 15:00:39
【问题描述】:

在我的 react-router 路由中,我使用了 plainRoutes,如下所示:

getComponent (nextState, cb) {
    require.ensure([], (require) => {
      const CoreLayout  = require('../layouts/CoreLayout/CoreLayout').default
      const userActions = require('../store/user').actions
      store.dispatch(userActions.fetch())
      cb(null, CoreLayout)
    })
},

现在我需要状态中的一些东西,因为我的 IndexRoute.fetch 完成之前是未定义的:

indexRoute: Default(store),

默认

import { injectReducer } from '../../store/reducers'

export default (store) => ({
  getComponent (nextState, cb) {
    const state = store.getState();
    require.ensure([], (require) => {
      const actions = require('../modules').actions
      store.dispatch(actions.fetch(state.list.selected))
      // snipped for brevity
      cb(null, Default)
    }, 'default')
  }
})

如何确保完成第一次异步提取?

【问题讨论】:

    标签: javascript reactjs redux react-router


    【解决方案1】:

    如果您的异步操作返回承诺,您可以使用then。例如:

    //actions.js

    export default function fetch(id) {
       return (dispatch) => 
         fetch('/getSomething?id=' + id)
           .then(response => {
             dispatch({
               type: FETCH
               payload: response
             })
           });
    }
    

    // 默认

      ...
      store.dispatch(actions.fetch(state.list.selected))
        .then(response => {
           cb(null, Default)
        });
      ...
    

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 2015-04-13
      • 1970-01-01
      • 2017-09-23
      • 2020-03-30
      • 1970-01-01
      • 2016-10-27
      • 2011-07-05
      • 1970-01-01
      相关资源
      最近更新 更多