欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

DvaJS的Subscription的使用

发布时间:2023/12/20 javascript 67 豆豆
生活随笔 收集整理的这篇文章主要介绍了 DvaJS的Subscription的使用 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

简介:
subscriptions是订阅,用于订阅一个数据源,然后根据需要dispatch相应的action。数据源可以是当前的时间、服务器的websocket连接、keyboard输入、geolocation变化、history路由变化等等。格式为({ dispatch, history }) => unsubscribe。

subscripition的用法:

异步数据初始化:
比如:当用户进入 /users 页面时,触发action users/fetch 加载用户数据。

app.model({subscriptions: {setup({ dispatch, history }) {history.listen(({ pathname }) => {if (pathname === '/users') {dispatch({type: 'users/fetch',});}})}} })

拓展:

path-to-regexp Package

如果url规则比较复杂,比如: /users/:userId/search ,那么匹配和userId的获取都会比较麻烦。这时推荐使用 path-to-regexp简化这部分逻辑。

import pathToRegexp from 'path-to-regexp';// in subscription const match = pathToRegexp('/users/:userId/search').exec(pathname); if (match) {const userId = match[1];// dispatch action with userId }

总结

以上是生活随笔为你收集整理的DvaJS的Subscription的使用的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。