使用HashHistory

时间:2016-12-15 09:45:51

标签: javascript reactjs react-router

我正在学习React并正在关注this教程。这是我的routes.js文件:

var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var historyHistory = ReactRouter.hashHistory;
var IndexRoute = ReactRouter.IndexRoute;


var Main = require('../components/Main');
var Home = require('../components/Home');


var routes = (
  <Router history={hashHistory}>
    <Route path='/' component={Main}>
      <IndexRoute path='/home' component={Home} />
    </Route>
  </Router>
);

module.exports = routes;

以及package.json中安装的依赖项:

  "dependencies": {
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-router": "^3.0.0"
  },
  "devDependencies": {
    "babel-core": "^6.20.0",
    "babel-loader": "^6.2.9",
    "babel-preset-react": "^6.16.0",
    "html-webpack-plugin": "^2.24.1",
    "webpack": "^1.14.0",
    "webpack-dev-server": "^1.16.2"
  }

使用此代码,我收到此错误: ReferenceError: hashHistory is not defined

如果我删除hashHistory,我会收到此错误: ReferenceError: history is not defined

我无法理解错误,如果我没有使用hashHistory,那么history是指向的错误?

罪魁祸首(存在于dist/index_bundle.js中,某些生成的代码)是:

  !history.getCurrentLocation ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'You have provided a history object created with history v2.x or ' + 'earlier. This version of React Router is only compatible with v3 ' + 'history objects. Please upgrade to history v3.x.') : (0, _invariant2.default)(false) : void 0;

2 个答案:

答案 0 :(得分:1)

您在第5行导入ReactRouter.hashHistory为var historyHistory。

因此,当您渲染路由器组件时,您应该执行history = {historyHistory}或将变量重命名为hashHistory。

编辑:完全遗漏历史时得到的错误是,因为历史是强制性的道具。

答案 1 :(得分:0)

只需在一行中导入所有必需的内容,例如:

import { Router, Route, IndexRoute, hashHistory } from 'react-router'

然后在渲染中使用这些相同的名称。