React Router不起作用

时间:2017-05-30 12:51:05

标签: reactjs

我使用React Router构建了一个简单的应用程序但是当我尝试启动该应用程序时,我在控制台中出现了两个错误:

  1. 道具historyRouter标记为必需,但其值为undefined

  2. 无法读取未定义的属性location

  3. 这是我的代码:

    var React = require('react');
    var ReactDOM = require('react-dom');
    var {Route, Router, IndexRoute, hashHistory} = require('react-router');
    var Main = require('Main');
    
    ReactDOM.render(
        <Router history={hashHistory}>
            <Route path="/" component={Main} />
        </Router>,
        document.getElementById('app')
    );
    

    和package.json文件:

    {
      "name": "boilerplate",
      "version": "1.0.0",
      "description": "Simple React App",
      "main": "ext.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "Milad Fattahi",
      "license": "ISC",
      "dependencies": {
        "express": "^4.15.3",
        "react": "^15.5.4",
        "react-dom": "^15.5.4",
        "react-router": "^4.1.1"
      },
      "devDependencies": {
        "babel-core": "^6.5.1",
        "babel-loader": "^6.2.2",
        "babel-preset-es2015": "^6.5.0",
        "babel-preset-react": "^6.5.0",
        "babel-preset-stage-0": "^6.24.1",
        "webpack": "^1.12.13"
      }
    }
    

    修改:

    我安装了react-router-dom并将我的代码的第三行更改为此但没有任何更改。

    var {Route, Router, Link} = require('react-router-dom');
    

1 个答案:

答案 0 :(得分:2)

使用v4,您可能还需要导入 react-router-dom 。我没有经过测试,但这应该可行。

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route,IndexRoute, hashHistory } from 'react-router-dom'
var Main = require('Main');


ReactDOM.render(
<Router history={hashHistory}>
    <Route path="/" component={Main} />
</Router>,
document.getElementById('app')
);

此外,使用v4,无需导入&#39; react-router&#39; 。 &#39; react-router-dom&#39; 会这样做。