效果图![在这里插入图片描述](https://img-blog.csdnimg.cn/f7324662374b488b9c35bf1fb78562c2.gif)
useSearchParam
import { useState, useEffect, useCallback } from 'react'
const useSearchParam = param =>
{
const getValue = useCallback(
() => new URLSearchParams(window.location.search).get(param),
[param]
);
const [value, setValue] = useState(getValue);
useEffect(() =>
{
const onChange = () =>
{
setValue(getValue());
};
window.addEventListener('popstate', onChange);
window.addEventListener('pushstate', onChange);
window.addEventListener('replacestate', onChange);
return () =>
{
window.removeEventListener('popstate', onChange);
window.removeEventListener('pushstate', onChange);
window.removeEventListener('replacestate', onChange);
};
}, []);
return value;
};
export default useSearchParam
index
import useSearchParam from './useSearchParam '
const params = {
name: 'name',
age: 'age',
sex: 'sex'
}
const index = () =>
{
const paramName = useSearchParam(params.name);
const paramAge = useSearchParam(params.age);
const paramSex = useSearchParam(params.sex);
return (
<div>
<p>参数值: {paramName || 'null'} {paramAge || 'null'} {paramSex || 'null'}</p>
<button
onClick={() => history.pushState({}, '', location.pathname + `?${params.name}=二弟&${params.age}=${17}&${params.sex}=${'女'}`)} >
查看
</button>
<button onClick={() => history.pushState({}, '', location.pathname)}>
退出
</button>
</div>
);
};
export default index