我是React JS的新手,正在尝试用它构建一个多页应用程序。我编写了以下代码来实现它:

routes.js

import React from 'react';
import { Route } from 'react-router-dom';
import App from './App';
import {FirstPage} from './Components/FirstPage';

export default (
    <Route excat path="/" component={App}>
        <Route path="/some/firstpage" component={FirstPage} />
    </Route>
);


index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Router} from 'react-router-dom';
import {HashRouter as history} from 'react-router-dom';
//import 'semantic-ui-css/semantic.min.css';
import './index.css';
import App from './App';
import routes from './routes.js';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
    <Router routes ={routes} history={history} />,
    <App />, document.getElementById('root'));
registerServiceWorker();


FirstPage.js

import React, { Component } from 'react';


export class FirstPage extends Component {
    render() {
        return (
            <div className="App">
                <header className="App-header">
                    <h1 className="App-title">Welcome to FirstPage</h1>
                </header>
                <p className="App-intro">
                </p>
            </div>
        );
    }
}


App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { Link } from 'react-router-dom';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
          <main>
              {this.props.children}
          </main>

        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
          <Link to="/some/firstpage">Click me</Link>
      </div>
    );
  }
}

export default App;


我得到的错误如下:

目标容器不是DOM元素。这指向index.js中的以下代码

./src/index.js
C:/.../frontend/src/index.js:11

   8 | import routes from './routes.js';
   9 | import registerServiceWorker from './registerServiceWorker';
  10 |
> 11 | ReactDOM.render(
  12 |     <Router routes ={routes} history={history} />,
  13 |     <App />, document.getElementById('root'));
  14 | registerServiceWorker();


我希望有人能帮助我并向我解释我做错了什么。

最佳答案

您对ReactDOM.render()的参数是错误的。将App组件包装在Router组件中:

ReactDOM.render(
  <Router routes ={routes} history={history} ><App /></Router>, document.getElementById('root')
);


https://reactjs.org/docs/react-dom.html#render

关于javascript - 多页面应用程序React Router v4,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46510047/

10-10 16:25