当搜索条件变化时,改变地址改变页面内容,达到页面和地址一一对应。
举个例子:
当查看所有用户时,是一个表格分页,用户翻页第二页时,地址添加参数,表示当前是用户页面的第二页。
// 默认页面
http://localhost:8080/system/users
// 翻页第二页
http://localhost:8080/system/users?page=2&pageSize=10
思路:添加地址栏监听函数,当加载是当前页时加载数据。
遇到的问题:1. 当直接在挂载函数里面,取地址栏的参数,然后加载数据时,不会有效。因为打开的是当前页的时候没有执行componentDidMount
。2. 特殊搜索参数需要字符串化,然后再特殊处理。
// 变量
const searchProps = [ // 搜索选项
{
key: 'name',
label: '用户名',
placeholder: '请输入名字...',
allowClear: true,
},
{
key: 'email',
label: '邮箱',
allowClear: true,
}
];
let currentHref = ""; //当前页面的路径,例如'system/users',去掉IP、端口、参数的URL
let listenValue: Function; // 路由监听,用于当前页面参数发生变化的数据加载
// 挂载函数添加监听事件
componentDidMount() {
//取当前界面的地址
const href = location.href;
currentHref = href.substring(href.indexOf("/", 7), href.indexOf("?") === -1 ? href.length : href.indexOf("?"));
listenValue = this.props.history.listen((route: any) => {
if (route.pathname === currentHref) {
const query = this.props.history.location.query;
const {
current = 1,
pageSize = 10,
} = query;
this.loadData({
pageSize,
current,
...query,
});
// 根据地址栏参数改变搜索框的值,搜索框值需要格式化时,在这处理
searchProps.forEach((v: SearchItem) => {
v.value = query[v.key]
});
}
});
}
// 搜索函数
handleSearch = (args: any) => {
args = Object.assign(args);
this.searchParams = {
...args,
current: 1,
};
this.handleOpen();
};
// 打开当前页带参数
handleOpen() {
router.push({
pathname: currentHref,
query: {
...this.searchParams,
},
});
}
// 加载数据函数
loadData = (args: Object) => {
const { dispatch } = this.props;
dispatch({
type: 'sysUser/fetch',
payload: {
...args,
}
});
};
// 取消挂载时,取消监听函数
componentWillUnmount() {
listenValue();
}