我正在学习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;

最佳答案

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

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

编辑:完全遗漏历史记录时出现的错误是,因为历史记录是强制性的。

关于javascript - 使用HashHistory时出现ReferenceError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41160996/

10-09 05:34