Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

javascript - Check history previous location before goBack() react router v4

My goal is to enable a "Go Back" button, but only if the route/path the user would go back to is in a certain category.

More precisely I have two kinds of Routes : /<someContent> and /graph/<graphId>. When the user navigates between graphs they should be able to go back to the previous graph but not to a /... route. This is why I can't simply run history.goBack(), I need to check the location first.

const history = createHashHistory();
const router = (
        <ConnectedRouter history={history}>
            <Switch>
                <Route exact path='/' component={Home}></Route>
                <Route exact path='/extension' component={Home}></Route>
                <Route exact path='/settings' component={Home}></Route>
                <Route exact path='/about' component={Home}></Route>
                <Route exact path='/search' component={Home}></Route>
                <Route exact path='/contact' component={Home}></Route>
                <Route path='/graph/:entityId' component={Graph}></Route>
            </Switch>
        </ConnectedRouter>
);

I'd like to implement something like this in the Graph component:

if (this.props.history.previousLocation().indexOf('graph') > -1){
    this.props.history.goBack();
} else {
    this.disableReturnButton();
}

This question also applies to goForward() as I'd like to disable the "forward" button if not applicable. Also the user moves around with this.props.history.push(newLocation)

Obviously I'd like to avoid using side-tricks like logging in localStorage or a redux store as the user moves around, it feels less natural and I know how to do it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While navigating though the Link component or even though history.push, you could pass the current location to another Route component

like

<Link to={{pathname: '/graph/1', state: { from: this.props.location.pathname }}} />

or

history.push({
  pathname: '/graph/1',
  state: { 
      from: this.props.location.pathname
  }
})

and then you could just get this location in your Component like this.props.location.state && this.props.location.state.from and then decide whether you wan't to goBack or not


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...