使用Umi的history向子页面传递数据

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部分为所需要的数据
在这里插入图片描述
总结Umihistory方法跳转页面、传递数据,主要是通过history内置的一些方法进行的,本文主要用到了history.push()history.location两种内置方法。其中history.push()进行路由的更改和数据的传递,history.location进行数据的接收。
如果有什么问题欢迎大家在评论区交流,我会尽可能进行解答。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值