前端封装一个url参数填入小组件附带

*前端封装一个url参数填入小组件附带(代码解析)

  1. 在工作的时候,通常我们会遇到各种参数的加添。
  2. 各种添加id,type,tabs之类的类型。参数。方便定位页面

在工作之中,将history封装成一个可控的方法,方便添加移除loaction.query。

二话不说附上代码

import { parse } from "query-string";

// TODO: 附着到  location,而不是 history
export function xxxHistory(history) {
  function addQuery(history) {
    history.location = Object.assign(history.location, {
      query: parse(history.location.search),
      addQuery: (k, v) => {
        const query = new URLSearchParams(history.location.search);
        query.set(k, v);
        history.replace(
          Object.assign(history.location, { search: query.toString() })
        );
        return query.toString();
      },
      replaceQuery: (obj: {}) => {
        const query = new URLSearchParams();
        Object.keys(obj).forEach(k => query.set(k, obj[k]));
        history.replace(
          Object.assign(history.location, { search: query.toString() })
        );
        return query.toString();
      },
      removeQuery: k => {
        const query = new URLSearchParams(history.location.search);
        query.delete(k);
        history.replace(
          Object.assign(history.location, { search: query.toString() })
        );
        return query.toString();
      }
    });
  }

  addQuery(history);
  history.listen(() => {
    addQuery(history);
  });
}

封装成一个方法之后,在全局的页面调用他/
主文件下面,app

import createBrowserHistory from 'history'
import {Router } from 'react-router'
const history=createBrowserHistory()
xxxHistory(history)

@withRouter
export class app extends React.Component{

   render(){
      return (
        <>
         <Router history={history}>
            <Route exact path=‘./dome’  render={(props) => {
              <Dome ...props/>
             }}>
         </Router>
        </>
        )
   }
}

BrowserHistory 是基于 html5 的现代浏览器的一种管理 history 的方式,是使用浏览器中的 History API 来处理 URL,也是 react router 推荐使用的一种方式。因为是使用真实的浏览器 history,就像 HTML 网页间的跳转一样,和浏览器的操作配合完美(浏览器自带的“后退”,“前进”,“刷新” 按钮,浏览器会记录浏览 history)。

createBrowserHistory 就是用于创建 BrowserHistory 对象,其中封装了 historty 的一些方法,比如前进,监听等等。
 

```xml
当其他页面需要调用的时候,例如首次加载页面的时候,判断页面是否有id的存在。
那么我们就可以利用这个封装的方法


import { withRouter } from 'react-router'
@withRouter
export class dome extends React.Component{
   componentDidMount(){
     this.props.location.removeQuery('xxx参数')//移除url参数
     this.props.location.addQuery('xxx参数',值)//增加参数-并且值
   }
   render(){
      return (
        <>
        <div>xxxxx</div>
        </>
        )
   }
}

this.props.location.removeQuery(‘xxx参数’) //移除url参数
this.props.location.addQuery(‘xxx参数’,值) //增加参数-并且值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值