未捕获类型错误:this.context.router.push不是函数

Uncaught TypeError: this.context.router.push is not a function

本文关键字:push router 函数 context this 类型 错误      更新时间:2023-09-26

正如帖子被调用一样,这就是我从浏览器控制台得到的。单击下拉按钮后,尝试更改到配置文件页面。代码:

contextTypes: {
    router: React.PropTypes.func
},
_handleProfile: function(e){
    this.context.router.push("profile");
},

<NavDropdown eventKey={3} title={this.props.email} id="collapsible-nav-dropdown">
    <MenuItem eventKey={1}>
        <Button className="dropdown-button" onClick={this._handleProfile} bsSize="small">
            Profile
        </Button>
    </MenuItem>
    <MenuItem divider />
    <MenuItem eventKey={2}>
        <Button  className="dropdown-button" onClick={this._handleLogout} bsSize="small">
            Logout
        </Button>
    </MenuItem>
</NavDropdown>

Using React.createClass,react-bootstrap,react-router

编辑:已添加路线。

var Router = (
    <Route name="app" path="/" handler={app}>
        <DefaultRoute handler={Index} />
        <Route name="login" path="login" handler={Login} />
        <Route name="profile" path="profile" handler={Profile} />
    </Route>
);

如果您使用的是最新的react路由器v4,则此问题的解决方案需要:

this.context.router.history.push('/path');

新的react router v4在访问this.context.router时更改了推送方法的位置。router现在有历史记录和路由作为属性,您可以在历史记录中找到分配的方法。

这可能不适合旧版本,因为v4已经重写,并且不向后兼容。由于这个问题是第一个出现在谷歌搜索关键字:

Uncaught TypeError: this.context.router.push is not a function

我已经在另一个线程中回答了类似的问题,我决定在这里添加相同的解释,以防未来的开发人员首先出现在这里。