this.props.history.push不起作用



当我导出一个类似的组件时:

export default class Link extends React.Component{
  onLogout() {
    this.props.history.push('/');
  }

绑定的按钮可以正确更改React-Router V4中的页面。

但是,在我的main.js文件中,我目前正在尝试获得类似的东西:

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

工作。但这只是给我一个类型错误。

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

我确实安装了所有正确的依赖项,并且在我的其他组件中效果很好。我目前正在主JS文件中有此IF语句(这是一个小型项目,我正在练习V4(,所以我认为这可能是因为我没有延长课程。

有人知道为什么相同的代码在主文件中不起作用,并且是否有解决方法?所有React-Router V4的变化都使这个新秀迷住了。

这意味着未定义this.props,因为您在回调中使用this.props,其中this不是您认为的。要解决这个问题,请使用这样的回调:

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

而不是

<button onClick={this.onLogout}>

您也可以做

import { browserHistory } from 'react-router'
... browserHistory.push('/');

编辑:关于后者,您还可以用以下组件包装组件:

import { withRouter } from 'react-router';
// in YourComponent:
... this.props.router.push('/');
export default withRouter(YourComponent);

它可能比browserHistory更好,因为您不必指定历史记录类型(可以更改为hashHistory并仍然有效(。

我建议您不要直接进入历史记录中的地址。

您可以将用户发送到页面,您可以有条件地检查他是否可以查看内容(如果是(,然后在渲染方法中渲染返回组件else else返回

这将导致一个清洁的代码。

https://github.com/reacttraining/react-router/blob/master/packages/react-router/docs/api/redirect.md

最新更新