*前端封装一个url参数填入小组件附带(代码解析)
- 在工作的时候,通常我们会遇到各种参数的加添。
- 各种添加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参数’,值) //增加参数-并且值