Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

history.js - React history.push() is updating url but not navigating to it in browser

I've read many things about react-router v4 and the npm history library to this point, but none seems to be helping me.

My code is functioning as expected up to the point when it should navigate and do a simple redirect when the url is changed using the history.push() method. The URL IS changing to the specified route, but not doing the redirect on the button push. Thanks in advance, still learning react-router...

I would like for the button push to do a simple redirect without the {forceRefresh:true}, which then reloads the whole page.

import React from 'react';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory({forceRefresh:true});

export default class Link extends React.Component {
  onLogout() {
    history.push("/signup");
  }
  render() {
      return(
        <div>
          <h1>Your Links</h1>
          <button onClick={this.onLogout.bind(this)}>Log Out</button>
        </div>
      )
  }
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You shouldn't need to downgrade to v3, React-Router 4.0.0 is totally capable of accomplishing what the OP asked for.

const history = createBrowserHistory();

is a custom history object so you should use <Router> to synchronize it with react-router instead of <BrowserRouter>, which is what I assumed you were using.

Try this instead:

import React, {Component} from 'react';
import { Router } from 'react-router';
import { Route } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';

const history = createHistory();   

class App extends Component {
   constructor(props){
      super(props);
   }
 
   render(){
       return (
           <Router history={history}>   //pass in your custom history object
                <Route exact path="/" component={Home} />
                <Route path="/other" component={Other} />
           <Router />
       )
   }
}

Once your custom history object is passed in via Router's history prop, history.push should work just as expected in anywhere of your app. (you might want to put your history object in a history config file and import it into places where you want to route programmatically).

For more info, see: React Router history object


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...