react-router v4 - browserHistory is undefined

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

问题:

I am creating my first react app in electron (my first electron app too). I have two routes & need to navigate from one to another. For that I am using following code:

Root

ReactDOM.render(   ,   document.getElementById('root') ); 

App

class App extends React.Component {     constructor() {         super();     }     render() {         return (             
) } }

Page

import { browserHistory } from 'react-router'; ... browserHistory.push('/city'); 

This line gives error,

TypeError: Cannot read property 'push' of undefined 

I searched web for possible solution but can't find one! There are many similar questions on SO too, but none of it worked for me :(

回答1:

You have to import it from the history module now.

Also you cannot use the browser history in an electron environment, use the hash or the memory one.

import { createHashHistory } from 'history'  const history = createHashHistory() 

You can then use the history injected in the props

this.props.history.push('/') 


回答2:

Useful pointers above. The simplest solution I've found is to add:

import {createBrowserHistory} from 'history'; 

to your list of import statements, then add:

const browserHistory = createBrowserHistory(); 

Might not work perfectly, but for the basic stuff I'm working on seems to do the trick. Hope that helps.



回答3:

Its is not working for your because in your component you are still using browserHistory which is not longer availabe from react-router package. You should change to using histroy from the history package

To simplify you can create a history.js file with the following contents

import { createBrowserHistory } from 'history'  export default createBrowserHistory(); 

Root

import history from '/path/to/history';  ReactDOM.render(   ,   document.getElementById('root') ); 

Page

import history from 'path/to/history'; ... history.push('/city'); 


回答4:

import { browserHistory } from 'react-router' does not work in React router 4. Link

Use the redirect component:

import { Redirect } from 'react-router'; 

The render function should replace the entire content with Redirect component.



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