效果图
![在这里插入图片描述](https://img-blog.csdnimg.cn/d38d3c8c1a8c4f63acdb031f0e9dca5f.gif)
JS
import { useState, useEffect, useCallback } from 'react';
const index = () =>
{
const useHash = () =>
{
const [hash, setHash] = useState(() => window.location.hash);
const hashChangeHandler = useCallback(() =>
{
setHash(window.location.hash);
}, []);
useEffect(() =>
{
window.addEventListener('hashchange', hashChangeHandler);
return () =>
{
window.removeEventListener('hashchange', hashChangeHandler);
};
}, []);
const updateHash = useCallback(
newHash =>
{
if (newHash !== hash) window.location.hash = newHash;
},
[hash]
);
return [hash, updateHash];
};
const [hash, setHash] = useHash();
useEffect(() =>
{
setHash('#chuan');
}, []);
return (
<div>
<p>当前的地址为:{window.location.href}</p>
<p>Edit hash: </p>
<input value={hash} onChange={e => setHash(e.target.value)} />
</div>
);
};
export default index