我用的是反应路由器。我想从我来自的地方检测上一个页面(在同一个应用程序中)。我的上下文中有路由器。但是,我看不到路由器对象上的任何属性,比如“前一条路径”或历史记录。我该怎么做呢?
发布于 2021-05-10 21:09:27
这个答案使用了与@AlexandrLazarev类似的方法,但通过React实现了它。这将确保捕获对路径的所有更改,而不管它们是如何启动的。前面的path值存储在顶层组件的状态中,然后可以作为道具传递给子组件,或者如果您使用的是像Redux这样的全局状态提供程序,则可以将其添加到存储中:
import { useEffect, useState } from 'react'
cont App = ({ location }) => {
const [currentPath, setCurrentPath] = useState(null);
const [previousPath, setPreviousPath] = useState(null);
useEffect(() => {
if (location.pathname !== currentPath) {
setPreviousPath(currentPath);
setCurrentPath(location.pathname);
}
}, [location.pathname]);
}标记中的实现类似于下面的代码片段。我一直在使用Reach路由器,但是考虑到它的被合并和React路由器,它也应该在那里工作。组件使它的所有子程序都可以使用location支柱,并在其pathname属性下保存当前路径的值。
<Router>
<App path="/*" />
<Router/>https://stackoverflow.com/questions/39288915
复制相似问题