前言
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' }) });
},
},

扩展
对于正则路径的判断,可以使用 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
网友评论