美文网首页
subscriptions订阅

subscriptions订阅

作者: 林ze宏 | 来源:发表于2018-11-10 23:59 被阅读0次

前言

subscriptions:可以理解为监听事件。订阅方法传入的props参数,为dispatch和history。
订阅的方法名可以随意,并没有规定,如下面的loginSub、clickPageSub等名称,也可以定义成 aa或者bb等。

声明

  subscriptions: {
    loginSub({ dispatch, history }) { 
      history.listen(location => { // history监听,使用listen方法
        if(location.pathname === '/counter') {
          dispatch({type: 'add'});
        }
      })
    },
    clickPageSub({dispatch, history}) {
      document.addEventListener('click', ()=> {
        dispatch({type: 'add'});
      })
    },
    keyboardWatcher({ dispatch }) {
      key('⌘+up, ctrl+up', () => { dispatch({ type: 'add' }) });
    },
  },



订阅props的值

扩展

对于正则路径的判断,可以使用 path-to-regexp 这个库。
如:

subscriptions: {
    loginSub({ dispatch, history }) {
      history.listen(location => {
        const flag = pathToRegexp('/counter').exec(location.pathname);
        if(flag) {
          dispatch({type: 'add'});
        }
      })
    },
    clickPageSub({dispatch, history}) {
      document.addEventListener('click', ()=> {
        dispatch({type: 'add'});
      })
    },
    keyboardWatcher({ dispatch }) {
      key('⌘+up, ctrl+up', () => { dispatch({ type: 'add' }) });
    },
  },


关于path-to-regexp可以结合一下中文参考:
PocketLibs(2)—— 请求相关 path-to-regexp

相关文章

网友评论

      本文标题:subscriptions订阅

      本文链接:https://www.haomeiwen.com/subject/soeoxqtx.html