无法使用React路由器功能

时间:2018-06-13 06:39:40

标签: reactjs react-router-v4

我正在使用react js与react路由器构建一个新的Web应用程序。当我启动应用程序时,收到错误为&#34; You should not use <Route> or withRouter() outside a <Router>&#34;。我已经分享了我的Main.js和Index.js文件。

enter image description here

Main.js:

import React, { Component } from "react";
import {Route,NavLink,HashRouter} from "react-router-dom";
import About from "./components/About";
import Contact from "./components/Contact";
import DashBoard from "./components/DashBoard";
import Home from "./components/Home";
import logo from './logo.svg';
import './App.css';

class Main extends Component {
  render() {
    return (
        <hashRouter>
        <div>
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
          <h1>Simple SPA</h1>
          <ul className="header">
            <li><NavLink  to="/">Home</NavLink ></li>
            <li><NavLink  to="/Dashboard">Dashboard</NavLink ></li>
            <li><NavLink  to="/About">About</NavLink ></li>
            <li><NavLink  to="/contact">Contact</NavLink ></li>
          </ul>
          <div className="content">
            <Route path="/" component={Home}/>
            <Route path="/Dashboard" component={DashBoard}/>
            <Route path="/contact" component={Contact}/>
          </div>
        </div>
        </hashRouter>
    );
  }
}

export default Main;

Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Main from './Main'
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<Main/>, document.getElementById('root'));

registerServiceWorker();

2 个答案:

答案 0 :(得分:1)

您的Router需要超出Main,因此您的index.js应如下所示:

ReactDOM.render(
    <HashRouter>
        <Main />
    </HashRouter>
), document.getElementById('root'));

答案 1 :(得分:0)

如果您想立即修复,只需更新 package.json 中的依赖项版本并重新安装。

“依赖项”:{ "google-map-react": "^1.1.5", "mdbreact": "^4.25.0", “反应”:“^ 16.12.0”, "react-dom": "^16.12.0", "react-router-dom": "^5.1.2", “反应脚本”:“3.3.0” },