ReactJS Router V4 history.push not working

I upgraded to React Router V4 and am now struggling with the method history.push.

I have an index.js file:

import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Route } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

import { Main} from "./components/Main";
import { About } from "./components/About";
import { Cars} from "./components/Cars";


class App extends React.Component {

render() {
    return (
        <BrowserRouter history={history}>

            <div>
                <Route path={"/"} component={Main} />
                <Route path={"/cars"} component={Cars}/>
                <Route path={"/about"} component={About}/>
            </div>
        </BrowserRouter>
    )
  }
}

render(<App/>, window.document.getElementById("app"));

And then I have another file where I added a simple one to return to a specific page that looks like this:

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

const history = createBrowserHistory();

export class Cars extends React.Component {
  navigateBack() {
    history.push('/')
  }

  render() {
    return(
        <div>
            <h3>Overview of Cars</h3>
            <p>Model: </p>
            <button onClick={this.navigateBack} className="btn btn-primary">Back</button>
        </div>
    )
  }
}

So, I can’t understand what is going on here. When I click the button, the URL changes to /, but that’s all. Is there anyone who can help me?

EDIT

I found out that it works when I do this:

this.props.history.push('/home')

and

<button onClick={this.onNavigateHome.bind(this)}

but does it seem wrong somehow ??

when i do

this.context.history.push('/home')

I get Cannot read property 'context' of null, but why? Is my installation <BrowserRouter>incorrect?

Anyway, thanks for the help :)

+17
source share
4

{withRouter} from 'react-router-dom'

export default withRouter(Cars)

+9

v4 this.context.history.push('/cart');
:

History React Router v4?

history.push BrowserRouter

+2

forceRefresh = {true} .

<BrowserRouter forceRefresh={true}>
0

( ):

rout.js

import React from 'react';
import { Route, Switch, Redirect } from 'react-router';
import { BrowserRouter } from 'react-router-dom';

const routes = (
  <div>
    <BrowserRouter>
      <Switch>
        <Route path="/login" component={Login} />
        <Route path="/home" component={Logged} />
      </Switch>
    </BrowserRouter>
  </div>
);

Login.js

componentWillReceiveProps = nextProps => {
    const { signedIn, history } = this.props;
    if (signedIn !== nextProps.signedIn && nextProps.signedIn) {
      history.push('/home');
    }
  };
export default withRouter(connect(mapStateToProps)(Login));

! , -

-1

Source: https://habr.com/ru/post/1016390/


All Articles