React路由跳转与传参

路由跳转功能由React Router提供,需要先理解history,history是为React Router提供核心功能的包,能轻松地在客户端为项目添加基于location的导航,这种功能对于单页应用至关重要。

安装依赖:

npm install --save history

存在三类history,分别是browser,hash,与 memory。history包提供每种history的创建方法。

1.首先定义history:

无论创建哪种history,最终都会得到一个几乎拥有相同属性与方法的对象。

import { createMemoryHistory as createHistory } from "history";
export const history = createHistory();

// import { createBrowserHistory } from 'history';
//export const history = createBrowserHistory();

//import { useHistory } from 'react-router-dom';
//export const history = useHistory();

2.路由跳转与传参:

history.push('/hierarchy', {name:'sunny'});

还可以传递箭头函数做为参数

        history.push('/hierarchy', {
          name: params.value.items.length > 0 ? params.value.items[0].data.name : "NULL",
          hellofunction: ()=>{console.log("hello world!!!")}
        });

3.获取参数:

路由跳转后,在目标组件中获取参数:

const Hierarchy = React.memo((props) => {
    console.log(props.location.state.name);
    //调用传递的函数参数
    props.location.state.hellofunction();
}

其中用到了location对象,什么是location?

history对象中最重要的属性就是location,location对象反映了当前应用所在的"位置"。其包含了pathname,state(参数), search,hash这种由'URL'派生出的属性。
此外,每一个location都拥有一个与之关联且独一无二的key。'key'用于特定location的识别,向特定location存储数据。
最后,location可以拥有与之相关的状态。这是一些固定的数据,并且不存在于URL之中。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值