多页面应用程序React Router v4

时间:2017-10-01 07:08:32

标签: javascript jquery node.js reactjs react-router

我对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();

我希望有人可以帮助我解释我做错了什么。

1 个答案:

答案 0 :(得分:1)

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

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

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