Subscription

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

异步数据初始化

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

  1. app.model({
  2. subscriptions: {
  3. setup({ dispatch, history }) {
  4. history.listen(({ pathname }) => {
  5. if (pathname === '/users') {
  6. dispatch({
  7. type: 'users/fetch',
  8. });
  9. }
  10. });
  11. },
  12. },
  13. });

path-to-regexp Package

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

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