在Umi
官方文档中,给出了两种跳转页面的方式,这篇文章主要讲解使用history
的方法进行跳转和传参的操作。
先给出代码
路由部分(.umirc.ts)
:
import { defineConfig } from 'umi';
export default defineConfig({
nodeModulesTransform: {
type: 'none',
},
routes: [
{ path: '/', component: '@/pages/index' }, //父页面路由
{ path: '/users', component: '@/pages/users/index' }, //子页面路由
],
fastRefresh: {},
});
父页面(src/pages/index.tsx)
:
import React, { useState } from 'react';
import { history } from 'umi';
export default function IndexPage() {
const [count,setCount]=useState(0)
const handleKip = () => { //跳转页面时进行的操作
history.push({ //umi文档规定的固定格式
pathname: '/users', //要跳转的路由
state: { //传递的数据
data:count
},
});
};
return (
<div>
<h1 className={styles.title}>Page index</h1>
<div>{count}</div>
<button onClick={()=>setCount(count+1)}>count+1</button>
<button onClick={handleKip}>跳转页面</button>
</div>
);
}
子页面(src/pages/users/index.tsx)
:
import React, { useState } from 'react';
import { history } from 'umi';
const UsersIndex = () => {
const handleBack = () => { //返回上一页面的操作
history.goBack();
};
//通过history传递的参数,子页面接收时使用history的内置location去接收
//此时打印出history.location可以看到父页面传来的参数
console.log(history.location)
//将我们需要的值赋给num,然后将其在页面上显示出来
const num = history.location.state.data;
return (
<div>
<div>{num}</div>
<button onClick={handleBack}>返回</button>
</div>
);
};
export default UsersIndex;
打印出的history.location
部分如下图所示,其中state
部分为所需要的数据
总结:Umi
的history
方法跳转页面、传递数据,主要是通过history
内置的一些方法进行的,本文主要用到了history.push()
和history.location
两种内置方法。其中history.push()
进行路由的更改和数据的传递,history.location
进行数据的接收。
如果有什么问题欢迎大家在评论区交流,我会尽可能进行解答。