最近在基于antd pro 2.0实现前端开发,遇到需要从页面A点击按钮跳转到页面B,并且需要将页面A中的某些属性值一起传递给B页面使用。在网上查了好久,自己也尝试了很多方式,总结出以下两种方式可行,两种方式均借助于umi实现。
注: 两种方式实现的路由,必须将路由链接添加到antd组件config/router.config.js中,如下示:
export default [
{
path: '/',
component: '../layouts/BasicLayout',
Routes: ['src/pages/Authorized'],
authority: ['admin', 'user'],
routes: [
// dashboard
{
path: '/dashboard',
name: 'dashboard',
icon: 'dashboard',
routes: [
{
path: '/dashboard/analysis', //子路径值必须以父路径为前缀
name: 'analysis', //若不想在菜单中显示,name可不配置
component: './Dashboard/Analysis', //为pages下页面路径
}
],
},
]
},
];
方式一,在A页面使用标签实现路由
1. 导入umi组件
import Link from 'umi/link';
2. 在页面需要位置加上标签,to属性所指链接为config/router.config.js中所配路由链接,可嵌套button使用。传值方式与url传值相同,采用?id=XX方式,多值用&间隔,如下:
3. 请求到达B页面后,日志显示location中内容:
方式,二,在A页面使用js实现路由
1. 导入umi组件,此组件是umi下router,非react下Router
import router from 'umi/router';
2.编写function,实现路由,使用router.push添加需要的路由。参数传递可放入query或state中
handleRouterPage = () => {
if (XXX) {
业务1
return;
} else if (YYY) {
业务2
return;
}
router.push({
pathname:'/dashboard/analysis',
query:{id:1},
state:{obj: {id:1}}
})
};
3. 在页面需要地方增加或其它可触发function的组件
4. 请求到达B页面后,日志显示location中内容:
在B页面中使用传递的值,本人业务需要,在componentDidMount中使用传递的值obj。两种实现方式在B页面取值方法相同,均通过location获取属性值。方式一种传递的值只会存在于query中,因此使用location.query.xxx获取即可
componentDidMount() {
const { location } = this.props;
let { localId } = this.props;
//state中取值
localId = location.state.obj.id;
//query中取值
localId = location.query.id;
if(localId != undefined) {
this.setState({
disableFlag: false
})
}
}