[英]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中的嵌套和动态路由的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.