Skip to content
Discussion options

You must be logged in to vote

这是 history.listen 的预期行为,不是 bug。

原因:

history.listen 只监听路由变化(即从一个路径跳转到另一个路径),而页面初始化加载时并不算一次路由"变化"——它是第一次加载,没有"从哪来",所以 listen 的回调不会触发。

你的代码中 xxxx1 会打印(说明 setup 执行了),但 xxxx2 不会在首次加载时打印,只有后续路由跳转时才会触发。

解决方案:在 setup 中手动处理一次初始路由。

app.model({
  subscriptions: {
    setup({ dispatch, history }) {
      // 1. 手动处理初始加载时的路由
      const { pathname } = history.location;
      if (pathname === '/users') {
        dispatch({ type: 'users/fetch' });
      }

      // 2. 监听后续路由变化
      history.listen(({ pathname }) => {
        if (pathname === '/users') {
          dispatch({ type: 'users/fetch' });
        }
      });
    },
  },
});

也可以封装得更简洁:

subscriptions: {
  setup({ dispatch, history }) {
    const h…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by parker-super
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants