【发布时间】:2016-09-20 00:20:15
【问题描述】:
似乎没有 API 方法可以检测您是否可以从应用中的当前页面返回。可以检查历史长度,但包括前向和后向堆栈。
我只想在用户真正可以返回时才显示返回按钮。
【问题讨论】:
标签: reactjs react-router html5-history
似乎没有 API 方法可以检测您是否可以从应用中的当前页面返回。可以检查历史长度,但包括前向和后向堆栈。
我只想在用户真正可以返回时才显示返回按钮。
【问题讨论】:
标签: reactjs react-router html5-history
它给出了'POP'和'PUSH'值using this.props.location.action
【讨论】:
您可以通过检查 location.history 是否 > 2 来做到这一点。
在您的应用中显示或不显示后退按钮的示例:
onBack={ history.length > 2 ? () => { history.goBack() } : null }
【讨论】:
2?
history.length 是 1),然后你转到下一页 #2(history.length 是 2),然后再到第 3 页(history.length 是 3 )。现在你从 #3 回到 #1,history.length 仍然是 3 但在第 #1 页你无处可退。
我想我找到了解决方法
调用 history.pushState() 或 history.replaceState() 不会触发 popstate 事件。 popstate 事件仅通过执行浏览器操作触发,例如在同一文档的两个历史记录条目之间导航时单击后退按钮(或在 JavaScript 中调用 history.back())。
我检查了它:反应路由器在状态下保存了一个关键属性: 在历史行走中,它可能包含如下数据: event.state: {key: "jr2go2", state: undefined}
当我们回到我们进入网站或应用程序的最后一页时,这个状态属性将为空: event.state: null ,
所以我们可以像这样用 redux + rxjs(例如)来处理它:
// epic
export const handleHistoryWalkEpic = () =>
fromEvent<PopStateEvent>(window, 'popstate')
.pipe(
map(event => setCanGoBack(!!event.state)),
)
// reducer
case NavigationBarActionsTypes.SET_CAN_GO_BACK:
return {
...state,
canGoBack: action.payload.canGoBack,
}
并且您应该在任何推送历史操作中将 canGoBack 设置为 true,您的任何路由器处理程序组件都可以:
componentWillUpdate(nextProps: any) {
let { location } = this.props;
if (nextProps.history.action === 'PUSH') {
this.props.setCanGoBack()
}
}
【讨论】:
你可以通过检查history.action来做到这一点,如果它的值是POP,那么就没有回去的路线了。这是我找到的唯一方法。
<Button
onClick={() => {
if (history.action !== 'POP') history.goBack();
}}
disabled={history.action === 'POP'}
/>
【讨论】:
您可以检查loction.key,如果您有表示您在应用内路由的位置键。但是,如果您不这样做,则意味着您来自应用程序之外,或者您只是在新标签页中打开应用程序等。
import { useHistory, useLocation } from "react-router-dom";
const HISTORY = useHistory();
const LOCATION = useLocation();
<Button
onClick={() => {
if (LOCATION.key) {
HISTORY.goBack();
}
}}
disabled={!LOCATION.key}
/>;
【讨论】: