小编典典

react-router v4-browserHistory未定义

reactjs

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

ReactDOM.render(
  <Router history={browserHistory}>
      <App />
  </Router>,
  document.getElementById('root')
);

应用程式

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>
        )
    }
}

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

这行给出了错误,

TypeError: Cannot read property 'push' of undefined

我在网上搜索了可能的解决方案,但找不到!SO上也有许多类似的问题,但是对我来说都没有作用:(


阅读 239

收藏
2020-07-22

共1个答案

小编典典

您现在必须从历史记录模块中导入它,该模块提供了3种不同的方法来创建不同的历史记录。

  • createBrowserHistory适用于支持历史记录API的现代Web浏览器
  • createMemoryHistory 用作参考实现,也可以在非DOM环境中使用,例如React Native或测试
  • createHashHistory 适用于旧版网络浏览器

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

import { createHashHistory } from 'history'

const history = createHashHistory()

然后,您可以使用history注入的道具

this.props.history.push('/')
2020-07-22