How to know if react-router can go back to display back button in react app

三世轮回 提交于 2020-11-30 10:56:20

问题


There seems to be no API way to detect if you can go back from the current page in an app. One can check the history length, but that includes the forward and backward stack.

I want to display the back button only when the user actually can go back.


回答1:


I think I found a workaround

There is onpopstate event:

Calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in JavaScript), when navigating between two history entries for the same document.

And I checked it: react router saves at state a key property: On history walking it may contains a data like: event.state: {key: "jr2go2", state: undefined}

And when we go back to last page on wich we entered the site or app, this state property will be null: event.state: null ,

So we can handle it with redux + rxjs (for example) like this:

// 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,
  }

And you should set canGoBack to true on any push history action, it's possible with your any router handler component:

componentWillUpdate(nextProps: any) {
    let { location } = this.props;

    if (nextProps.history.action === 'PUSH') {
      this.props.setCanGoBack()
    }
}



回答2:


You can do it by checking if location.history is > 2.

Example to show or not the back button in your app:

onBack={ history.length > 2 ? () => { history.goBack() } : null }



回答3:


it gives 'POP' and 'PUSH' value using this.props.location.action



来源:https://stackoverflow.com/questions/37385570/how-to-know-if-react-router-can-go-back-to-display-back-button-in-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!