简体   繁体   中英

this.props.history.push not working

When i export a component like:

export default class Link extends React.Component{

  onLogout() {
    this.props.history.push('/');
  }

the button that this is tied to correctly changes the page in react-router v4.

However, in my main.js file, I am currently trying to get something like:

if (insert conditional here) {
    this.props.history.push('/');
  }

to work. But it just give me a type error.

'Uncaught TypeError: Cannot read property 'history' of undefined'.

I do have all the correct dependencies installed, and it works just fine in my other component. I'm currently having this if statement in the main js file (its a small project im practicing to understand v4), so I'm thinking it might be because I'm not extending a class.

Does anyone have any idea why the same code wouldn't be working in the main file, and is there a workaround for this? All the react-router v4 changes are befuddling this rookie.

This means that this.props is not defined, because you are using this.props in a callback where this is not what you think it is. To solve this, use your callback like this:

<button onClick={this.onLogout.bind(this)}>

instead of

<button onClick={this.onLogout}>

You can also do

import { browserHistory } from 'react-router'

... browserHistory.push('/');

Edit: Regarding the latter, you can also wrap your component with this:

import { withRouter } from 'react-router';

// in YourComponent:
... this.props.router.push('/');

export default withRouter(YourComponent);

It may be better than browserHistory because you don't have to specify the history type (could be changed to hashHistory and still work).

I would suggest you to not a address directly into the history but use .

You can send the user to the page and you can conditionally check if he is allowed to see the content if yes then render in render method return the component else return

This would result in a cleaner code.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md

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