phi*_*ilk 11 html5-history reactjs react-router
似乎没有API方法来检测您是否可以从应用程序中的当前页面返回.可以检查历史长度,但包括前向和后向堆栈.
我只想在用户实际可以返回时显示后退按钮.
Tug*_*dız 23
您可以检查location.key
您是否有位置键,这意味着您在应用程序内进行了路由。但如果您不这样做,则意味着您来自应用程序外部,或者您只是在新选项卡中打开应用程序等。
import { useHistory, useLocation } from "react-router-dom";
const history = useHistory();
const location = useLocation();
<Button
onClick={() => {
if (location.key) {
history.goBack();
}
}}
disabled={!location.key}
/>;
Run Code Online (Sandbox Code Playgroud)
对于 V6 及更新版本:
import { useHistory, useLocation } from "react-router-dom";
const history = useHistory();
const location = useLocation();
<Button
onClick={() => {
if (location.key !== 'default') {
history.goBack();
}
}}
disabled={location.key === 'default'}
/>;
Run Code Online (Sandbox Code Playgroud)
您可以通过检查history.action
其值是否为 来实现POP
,然后就没有返回的路径。这是我找到的唯一方法。
<Button
onClick={() => {
if (history.action !== 'POP') history.goBack();
}}
disabled={history.action === 'POP'}
/>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1326 次 |
最近记录: |