dva icon indicating copy to clipboard operation
dva copied to clipboard

saga watcher启动位置问题

Open MrCuriosity opened this issue 9 years ago • 4 comments

有一个自建的watcher用来处理response success

*watcher(action, { take, select, put, call }) {
  try {
    const action = yield take('CaseDetail/REQUEST_SUCCESS')
    /** 这里处理一些增删改之后的刷新列表操作 */
  } catch(e) {
    console.error('Users saga watcher error ->', e)
  }
}

目前watcher启动如下

subscriptions: {
  setup({ dispatch, history }) {
    history.listen((location, action) => {
      if (/^\/this\/route$/.test(location.pathname) && location.action.toUpperCase() !== 'REPLACE') {
        /** 一些init的dispatch */
        if (!window.sagaWatcher_thisRoute) {
          dispatch({ type: 'watcher' })
          window.sagaWatcher_thisRoute = 'thisRoute'
          console.log('thisRoute watcher setted up')
        }
      }
    })
  }
}

如果不判断!window.sagaWatcher_thisRoute,那么每进一次路由就会建一个watcher,response成功后就会刷新几次;但挂在window上又感觉不是很好,有没有合适点的做法?

MrCuriosity avatar Jun 29 '17 02:06 MrCuriosity

在 route 组件的 onEnter 上试试呢

zjxpcyc avatar Jun 30 '17 09:06 zjxpcyc

@zjxpcyc 对的,我想了一下,RouterConfig({ app, dispatch }) {}可以获得app实例,这里路由钩子onEnter、app._store.dispatch可以判断watcher是不是已经挂在app上,做法有点迂回,总也比挂在window上好多了

MrCuriosity avatar Jun 30 '17 12:06 MrCuriosity

我在想是不是应该保证一个常驻的watcher呢,在watcher底部,再次dispatch({ type: 'watcher' })不知可不可以,其实我在项目中没有尝试用过wathcer呢~

yangbin1994 avatar Jul 01 '17 02:07 yangbin1994

https://github.com/dvajs/dva/issues/1028#issuecomment-312433555

nihgwu avatar Jul 02 '17 00:07 nihgwu