以下是 Umi 中 history.push
的详细解析,涵盖其核心功能、参数传递方式、接收方法及注意事项,结合最新版本(Umi 4)的最佳实践:
📌 一、history.push
的核心作用
history.push
是 Umi 内置的路由跳转方法,用于编程式导航。它会将新路由添加到浏览历史栈中,实现页面跳转并传递参数。
📤 二、参数传递的三种方式
1. 查询参数(Query)
- 传递方式:
// 字符串形式 history.push('/list?id=123&name=umi'); // 对象形式(推荐) history.push({ pathname: '/list', search: '?id=123&name=umi', // 或使用 `query: { id:123, name:'umi' }`(部分版本兼容) });
- 特点:
- 参数暴露在 URL 中(如
/list?id=123
)。 - 刷新页面后参数保留。
- 参数暴露在 URL 中(如
2. 动态路由参数(Params)
- 传递方式:
// 路由配置:{ path: '/user/:id', component: './User' } history.push('/user/123');
- 接收方式:
import { useParams } from 'umi'; const { id } = useParams(); // id = '123'
- 特点:
- 参数嵌入 URL 路径(如
/user/123
),需提前配置动态路由。
- 参数嵌入 URL 路径(如
3. 状态参数(State)
- 传递方式:
history.push({ pathname: '/detail', state: { data: { id: 123, name: 'umi' } }, // 任意数据 });
- 接收方式:
import { useLocation } from 'umi'; const location = useLocation(); const data = location.state?.data; // { id:123, name:'umi' }
- 特点:
- 参数不暴露在 URL 中,通过内存传递。
- 刷新页面后参数丢失(Hash 路由模式下必丢,Browser 路由可能保留)。
📥 三、接收参数的常用方法
参数类型 | 接收方式 | 适用场景 |
---|---|---|
Query | const location = useLocation(); const id = new URLSearchParams(location.search).get('id'); | URL 显式参数 |
Params | const { id } = useParams(); | 动态路由参数 |
State | const location = useLocation(); const data = location.state; | 敏感数据或复杂对象 |
💡 提示:类组件可通过
this.props.location
获取参数。
⚠️ 四、Umi 4 的重要变更
-
**
query
属性弃用:
Umi 4 中history.push
的query
参数已废弃,需改用 search
(字符串)或state
** 。// Umi 3:history.push({ pathname:'/list', query:{ id:123 } }); // Umi 4:history.push({ pathname:'/list', search:'?id=123' });
-
新增第二个参数:
可直接传递状态对象作为第二个参数:history.push('/detail', { data: { id: 123 } }); // Umi 4 专属 const location = useLocation(); const data = location.state; // { data: { id:123 } }
🛠️ 五、注意事项
- 刷新后参数丢失:
state
参数在页面刷新后会丢失,敏感数据建议用query
或params
。 - 路由配置匹配:
跳转路径需在.umirc.ts
或配置文件中明确定义,否则跳转后页面空白。 - 编码问题:
search
参数含中文时需手动编码:history.push({ pathname:'/list', search: `?name=${encodeURIComponent('优米')}` });
💎 六、完整示例
跳转页面(传递参数):
import { history } from 'umi';
// 传递 state + query
history.push({
pathname: '/user',
search: '?id=123',
state: { from: 'home' },
});
目标页面(接收参数):
import { useLocation } from 'umi';
const UserPage = () => {
const location = useLocation();
const id = new URLSearchParams(location.search).get('id'); // '123'
const from = location.state?.from; // 'home'
return <div>ID: {id}, From: {from}</div>;
};
⚡ 总结
功能 | 推荐方式 | 注意点 |
---|---|---|
显式传递简单参数 | Query(search 字符串) | 需手动编码中文 |
隐藏传递复杂对象 | State(state 对象) | 刷新丢失,适合临时数据 |
结构化路由参数 | Params(动态路由) | 需预先配置路由 |
Umi 4 兼容性 | 弃用 query ,改用 search /state | 第二个参数直接传状态 |
遇到页面空白时,优先检查 路由配置 和 参数接收逻辑 。