gpt4 book ai didi

react-router - React Router v4 - 如何检测后退按钮导航与 url 刷新?

转载 作者:行者123 更新时间:2023-12-03 09:24:25 25 4
gpt4 key购买 nike

我的网址是 /page (A 页) 我想检测页面是否从 返回的历史记录导航到的位置(B 页) 或者如果用户在 (A 页) 并从 URL 栏刷新按钮手动刷新页面(不使用历史记录)。

我通过 react 路由器查看了所有历史记录、位置、 Prop ,但没有找到一种方法来区分用户如何导航到页面。

在这两种情况下,history.action == 'POP'是历史 Action 。理想情况下应该是 'POP'当应用程序中的后退按钮从b页返回到a页时,在a页时,刷新页面时,它不是'POP'喜欢 'REFRESH'例如。

我们如何区分它们以在我们的应用程序中运行不同的逻辑,因为两者都会触发 'POP' ?

最佳答案

您可以比较路径名,而不是比较历史记录键,例如,如果您在页面“/page1/page2”中并点击刷新,则新位置是相同的。但是如果你点击后退 Action ,新位置将是“/page1/”。

此解决方案还使用监听器来监听来自历史记录的任何操作。

  componentDidMount() {
const unlisten = history.listen((location, action) => {
if (action == 'POP') {
\\ thisLocation is the current location of your page
if (location.pathname != '/thisLocation/') {
alert('Back Pressed: ' + String(location.pathname));
} else {
alert('Refreshed: ' + String(location.pathname));
}
}
});
this.setState({ ...this.state, unlisten: unlisten });
}

componentWillUnmount() {
this.state.unlisten();
}

您可以在 Rei Dien 提供的链接中查看更多详细信息,作为您问题的评论: https://www.npmjs.com/package/history

[编辑]

另一种方法是使用 https://www.npmjs.com/package/react-router-last-location并这样做:
import { useLastLocation } from 'react-router-last-location';

componentDidMount() {
const unlisten = history.listen((location, action) => {
const lastLocation = useLastLocation();
if (location.pathname == lastLocation.pathname) {
alert('Back Pressed: ' + String(location.pathname));
}
}
});
this.setState({ ...this.state, unlisten: unlisten });
}

componentWillUnmount() {
this.state.unlisten();
}

不利的一面是,激活后退操作或单击转到您之前所在页面的链接之间没有区别,两者都会被检测为按下后退。如果您不想要一个新的依赖项,您可以按照 https://github.com/ReactTraining/react-router/issues/1066#issuecomment-412907443 中的说明手动完成。创建一个中间件。

关于react-router - React Router v4 - 如何检测后退按钮导航与 url 刷新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45992089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com