简体   繁体   English

this.props.history.push不起作用

[英]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. 绑定到的按钮可以正确更改react-router v4中的页面。

However, in my main.js file, I am currently trying to get something like: 但是,在我的main.js文件中,我目前正在尝试获取以下内容:

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. 我目前在主js文件中有这个if语句(这是一个旨在了解v4的小项目),所以我在想这可能是因为我没有扩展类。

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. react-router v4的所有更改都使这个菜鸟感到困惑。

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. 这意味着this.props ,因为您正在回调中使用this.props ,而this并不是您认为的那样。 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). 它可能比browserHistory更好,因为您不必指定历史记录类型(可以更改为hashHistory并仍然可以使用)。

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 您可以将用户发送到页面,并且可以有条件地检查用户是否被允许查看内容(如果是),然后在render方法中进行渲染;返回组件;否则返回

This would result in a cleaner code. 这将导致代码更简洁。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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