我对学习反应非常陌生,已经开始在react.js中使用Router。
当我尝试制作路由器时,出现此错误A <Router> may have only one child element Error in react

我的代码如下:

文件:Index.js

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

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


档案:App.js

import React, { Component } from 'react';
import {
  Route,
  NavLink,
  HashRouter
} from "react-router-dom";
import Home from "./Home";
import Stuff from "./Stuff";
import Contact from "./Contact";

class App extends Component {
  render() {
    return (
      <HashRouter>
      <div>
        <div>
          <h1>Simple SPA</h1>
          <ul className="header">
           <li><NavLink to="/">Home</NavLink></li>
            <li><NavLink to="/stuff">Stuff</NavLink></li>
            <li><NavLink to="/contact">Contact</NavLink></li>
          </ul>
          </div>
         <div className="content">
            <Route exact path="/" component={Home}/>
            <Route path="/stuff" component={Stuff}/>
            <Route path="/contact" component={Contact}/>
          </div>
        </div>
      </HashRouter>
    );
  }
} export default App;


对于Home.js,Stuff.js和Contact.js,有单独的文件。

我什至尝试使用Switch,但仍然遇到相同的错误。
有人可以建议出什么问题吗?

最佳答案

您的App.js看起来不错。真奇怪您确定您已构建此代码?

您可以尝试将index.js更改为:

import React from 'react';
import {
  HashRouter
} from "react-router-dom";
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

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


然后从App.js中删除HashRouter。检查是否有帮助。

10-07 16:22
查看更多