似乎没有 API 方法可以检测您是否可以从应用程序中的当前页面返回。人们可以检查历史长度,但这包括前向和后向堆栈。
我想仅当用户实际上可以返回时才显示后退按钮。
最佳答案
如果您有表示您在应用内进行路由的位置键,则可以检查 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}
/>;
对于 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'}
/>;
关于reactjs - 如何知道react-router是否可以返回并在react应用程序中显示后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37385570/