umi4 model的 subscriptions 对于 history 变化的监听在页面初始化的时候无效 #13269
Answered
by
Jerry-CodeHub
parker-super
asked this question in
Q&A
|
文档: |
Answered by
Jerry-CodeHub
Mar 20, 2026
Replies: 1 comment
|
这是 原因:
你的代码中 解决方案:在 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 handleRoute = (pathname: string) => {
if (pathname === '/users') {
dispatch({ type: 'users/fetch' });
}
};
// 初始加载
handleRoute(history.location.pathname);
// 后续变化
history.listen(({ pathname }) => handleRoute(pathname));
},
},额外说明: 如果你是从 Umi3 升级到 Umi4 的,需要注意 // Umi3 写法(不适用于 Umi4)
history.listen((location, action) => { ... })
// Umi4 正确写法
history.listen(({ location, action }) => { ... })
// 或者直接解构 pathname
history.listen(({ pathname }) => { ... }) |
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
这是
history.listen的预期行为,不是 bug。原因:
history.listen只监听路由变化(即从一个路径跳转到另一个路径),而页面初始化加载时并不算一次路由"变化"——它是第一次加载,没有"从哪来",所以listen的回调不会触发。你的代码中
xxxx1会打印(说明setup执行了),但xxxx2不会在首次加载时打印,只有后续路由跳转时才会触发。解决方案:在
setup中手动处理一次初始路由。也可以封装得更简洁: