我有一个应用程序,其中我将存储状态设置如下:
history.replace(location.pathname, {myValue: 1});
我知道,清除它的一种方法是执行history.replace(location.pathname, {});
但是我想知道,用什么其他方式代替这种状态?
当我点击<Link to={"/new/url"}/>
时似乎会发生这种情况,但是还有其他情况吗?该状态的持久性如何?
答案 0 :(得分:0)
如果您使用Redux,最简单的方法是使用connected-react-router。 否则,您必须自己构建它。
基本上,您需要有一个侦听器来捕获事件“ popstate”。
每次激活状态时,都会将popstate事件调度到窗口 历史记录条目在两个相同的历史记录条目之间更改 文件 (Mozila MDN Web docs)
这是一个非常基本的示例:
function useLocation () {
const [location, setLocation] = useState(window.location)
useEffect(() => {
window.addEventListener('popstate', handleChange)
return () => window.removeEventListener('popstate', handleChange)
}, [])
const handleChange = ()=> setLocation(window.location);
}