简体   繁体   中英

React Router history.goBack doesn't work when using <Redirect />

In a React App, I use Router like this:

let path='/';
if(condition){
   path='/dashboard'
}else if(condition){
   path='/login'
}

<Router>
 <Redirect to={path} />
   <Switch>
      <Route path="/dashboard"><Dashboard /></Route>
      <Route path="/login"><Login /></Route>
    </Switch>
</Router>

This works fine. But I want to implement a Back Button in each page to move along pages. I do this:

// The login.jsx component
function Post(props) {
  return (
    <div>
      <button type="button" onClick={() => props.history.goBack()}>
        Go back
      </button>
    </div>
  );
}

But I get this error:

Uncaught TypeError: Cannot read property 'goBack' of undefined

Then I follow another approach. I use useHistory :

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
  Link,
  useHistory,
} from "react-router-dom";

// The login.jsx component
function Post(props) {
  let history = useHistory();
  
  return (
    <div>
      <button type="button" onClick={() => history.goBack()}>
        Go back
      </button>
    </div>
  );
}

And this time when I click on the Go Back button, nothing happens!

If I do this procedures with <Link/> it works fine. But when I use <Redirect /> approach, it doesn't work. is there any alternative to my redirect approach? or is there any solution to current approach? thanks.

For redirects to be included in the history, use push

<Redirect push to={path} />

More information here from the docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM