React browserHistory.push giving Uncaught TypeErro

2020-08-02 20:00发布

问题:

I am trying to change the page on click. Here is the click function

import React, { Component } from 'react';
import {BrowserRouter as Router,Route} from 'react-router-dom';
import { browserHistory } from 'react-router';
class Buttons extends Component {
skipClick(){
    browserHistory.push('/sessionstate2');
}
render() {
return (<a className={skipShow} onClick={this.skipClick}>Skip</a>)
}
}

and index.js

import browserHistory from 'react-router';
ReactDOM.render(
    <Router history={browserHistory}>
    <div>
      <Route exact path="/" component={App} />
      <Route exact path="/sessionstate1" component={Template1}/>
      <Route exact path="/sessionstate2" component={Template2}/>
      <Route exact path="/sessionstate3" component={Template3}/>
</div>
  </Router>,
   document.getElementById('root')
 );

It is giving

Uncaught TypeError: Cannot read property 'push' of undefined

Can you please tell me what am I doing wrong here?

回答1:

Here's a reproducible example of how to programmatically change routes in react router v4.

First, install the boilerplate for a simple app:

sudo npm install -g create-react-app
create-react-app demo-app
cd demo-app
npm install react-router-dom

Then we'll change /src/App.js to:

import React from 'react'
import {BrowserRouter as Router, Route, Link, withRouter} from 'react-router-dom'

const BasicExample = () => (
  <Router>
    <div>
      <li><Link to="/">Home</Link></li>
      <li><Link to="/about">About</Link></li>

      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
    </div>
  </Router>
)

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)

const Button = withRouter(({history}) => (
  <button type='button' onClick={() => { history.push('/new-location') }}>Click Me!</button>
))

const About = () => (
  <div>
    <h2>About</h2>
    <Button />
  </div>
)

export default BasicExample

Then start your server:

npm run start

If you navigate to localhost:3000, then click About, you'll see the button component. Clicking it will programmatically change the route to /new-location



回答2:

You don't need to use browserHistory anymore. React-router-dom inject into your component route related props and context. One of these props is 'history' and on this history object is a function push that you can call and pass the route you want to navigate to.

example in a Class base component, you can create a function like below as an onClick handler to redirect to specific link

redirectToSessionStatePage() {
 this.props.history.push('/sessionstate2'); OR
 this.context.router.history.push('/sessionstate2');
}

while in a function base stateless component

redirectToSessionStatePage() {
 props.history.push('/sessionstate2'); OR
 context.router.history.push('/sessionstate2');
}