【问题标题】:ReactJS this.props.history.push doesn't exists! this.props doesn't include historyReactJS this.props.history.push 不存在! this.props 不包括历史
【发布时间】:2019-07-17 21:27:42
【问题描述】:

在 App.js 中,我管理路由(在下方)。在这两个课程中我都有

import {browserHistory} from "react-router";

当我单击图像时,控制台显示错误无法读取未定义的属性“推送”。所以我的道具不包括历史对象。如何使用 browserHistory 重定向用户?

////

    <Router history={browserHistory}>
    <div>
    <Route path="/profile" component={MyProfile} />
    </div
    </Router>

/// The code above is in a different class

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

    return (
    <React.Fragment>
    <img src="../images/my-profile.png" alt="profile" className="myprofile" id="myprofile" onClick={this.myprofile.bind(this)} />
    </React.Fragment>
    );

【问题讨论】:

  • 你试过把组件包裹在withRouter()吗?
  • 不需要this,只需props.history.push
  • props 的参数 myprofile() 似乎命名错误。实际上是 onClick 中的 event 称为 @Meir
  • 看来您应该用&lt;Link/&gt; 组件包装您的&lt;img/&gt; 标签,而不是尝试使用Router.push() 强制导航

标签: javascript reactjs redirect missing-data browser-history


【解决方案1】:

如果您尝试使用未在您的路由中定义的组件中的 this.history.push 方法,您也需要将所有路由器包装在“BrowserRouter”组件中,而不是使用“withRouter(组件名称)”。

【讨论】:

    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 2015-03-23
    • 2018-04-09
    • 1970-01-01
    • 2017-01-25
    • 2020-03-22
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多