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

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

I try to do a simple redirect in a function...

I tried this:

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

But then I got this error:

Uncaught TypeError: Cannot read property 'push' of undefined 

whats my fail?

回答1:

Creating a new browserHistory won't work because <BrowserRouter> creates its own history instance, and listens for changes on that. So a different instance will change the url but not update the <BrowserRouter>.

browserHistory is not available form react-router-dom package from v4 , and is separated to history package.

Navigating with WithRouter

You can rather make use of withRouter Higher Order Component and navigate with history prop

From the official documentation

You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.

Sample snippet

import {withRouter} from "react-router";   class MyComponent extends React.Component {    ...    changeRoute = () => {         this.props.history.push('/dashboard)    }    ... }    export default withRouter(MyComponent); 

Also see this answer for more info on nesting and dynamically routing in react-router-v4

Nesting routes and dynamically routing in React-router v4



回答2:

As mentioned in the comments you should use this new approach for v4 react router but if you are looking for a quick workaround you can use context. ```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 } 

This should do the trick



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!