繁体   English   中英

使用browserHistory.push动态更改路由不适用于react-router v4

[英]Using browserHistory.push to change Route dynamically doesn't work with react-router v4

我尝试在函数中执行简单的重定向...

我尝试了这个:

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

但是后来我得到了这个错误:

Uncaught TypeError: Cannot read property 'push' of undefined

我的失败是什么?

如评论中所述,您应该对v4 react router使用这种新方法,但是如果您正在寻找一种快速的解决方法,则可以使用上下文。 ```的JavaScript

import { PropTypes } from 'prop-types'
import React from 'react'

export default class MyComponent extends React.Component {
    ...

    // redirect to dashboard
    redirectToDashboard = () => {
        this.context.router.history.push('/dashboard');
    }
}

MyComponent.contextTypes = {
    router: PropTypes.object
}

这应该可以解决问题

创建一个新的browserHistory不会起作用,因为<BrowserRouter>创造自己的历史实例,并侦听的更改。 因此,其他实例将更改URL,但不会更新<BrowserRouter>.

v4 ,无法从react-router-dom软件包使用browserHistory ,并将其分离到history软件包中。

使用WithRouter导航

您可以宁愿使用withRouter高阶组件并使用history道具navigate

官方文件

您可以通过withRouter高阶组件访问历史对象的属性和最接近的<Route>'s匹配项。 withRouter路线更改时, withRouter都会使用与<Route>渲染props: { match, location, history }.相同的道具来重新渲染其组件props: { match, location, history }.

样本片段

import {withRouter} from "react-router"; 

class MyComponent extends React.Component {
   ...
   changeRoute = () => {
        this.props.history.push('/dashboard)
   }
   ...
}


 export default withRouter(MyComponent);

另请参阅此答案以获取有关react-router-v4中的嵌套和动态路由的更多信息

在React-router v4中嵌套路由和动态路由

暂无
暂无

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

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