BrowserHistory永远不会在ReactJS中初始化

时间:2017-03-15 10:18:07

标签: reactjs react-router

我对ReactJS很新。我正在尝试一些教程来做路由,但最终出现错误,其中" browserHistory"未定义。代码和错误消息如下所示。

Main.js

'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, IndexRoute, hashHistory,browserHistory} from 'react-router';
import App from './App.jsx';
import {Home,About,Contact} from './App.jsx';


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

来自浏览器控制台的错误消息

  

警告:道具类型失败:道具history被标记为必需   Router,但在路由器

中的值为undefined

请告知我实施是否已过时,或者我是否错过任何图书馆以解决此问题

3 个答案:

答案 0 :(得分:1)

我想我找到了原因,新的react-router不再支持browserHistory了。为了实现相同的目标,我使用了以下代码。

import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

答案 1 :(得分:0)

您可以尝试useRouterHistory

import { useRouterHistory } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';

const createAppHistory = useRouterHistory(createBrowserHistory);

const history = createAppHistory({
 parseQueryString: parse,
 stringifyQuery: stringify
})

<Router history={history}/>

答案 2 :(得分:0)

React Router v4改变了一切。他们制作了单独的顶级路由器元素。在代码中将<Router history={hashHistory}>替换为<HashRouter>

import {HashRouter,Route} from 'react-router-dom';

<HashRouter>
    <Route path = "/" component = {App} />
</HashRouter>