react-router v4 - browserHistory 未定义 [英] react-router v4 - browserHistory is undefined

查看:27
本文介绍了react-router v4 - browserHistory 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用电子创建我的第一个 React 应用程序(也是我的第一个电子应用程序).我有两条路线&需要从一个导航到另一个.为此,我使用以下代码:

根目录

ReactDOM.render(<路由器历史={browserHistory}><应用程序/></路由器>,document.getElementById('root'));

应用

class App 扩展 React.Component {构造函数(){极好的();}使成为() {返回 (<div className="app-master"><开关><Route path='/city' component={CityList}/><Route path='/' component={SplashScreen}/></开关>

)}}

页面

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

这一行给出了错误,

TypeError: 无法读取未定义的属性 'push'

我在网上搜索了可能的解决方案,但找不到!SO上也有很多类似的问题,但没有一个对我有用:(

解决方案

您必须从 历史记录中导入它

a> 模块现在提供 3 种不同的方法来创建不同的历史记录.

您不能在电子环境中使用浏览器历史记录,使用哈希或内存.

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

然后就可以使用注入到 props 中的 history

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

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(
  <Router history={browserHistory}>
      <App />
  </Router>,
  document.getElementById('root')
);

App

class App extends React.Component {
    constructor() {
        super();
    }
    render() {
        return (
            <div className="app-master">
                <Switch>
                    <Route path='/city' component={CityList}/>
                    <Route path='/' component={SplashScreen}/>
                </Switch>
            </div>
        )
    }
}

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 :(

解决方案

You have to import it from the history module now which provides 3 different methods to create different histories.

  • createBrowserHistory is for use in modern web browsers that support the history API
  • createMemoryHistory is used as a reference implementation and may also be used in non-DOM environments, like React Native or tests
  • createHashHistory for legacy web browsers

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('/')

这篇关于react-router v4 - browserHistory 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆