2017-10-01 68 views
0

我對React JS非常陌生,並試圖用它構建一個多頁面應用程序。我寫了下面的代碼來實現它:多頁面應用程序React Router v4

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

您對ReactDOM.render()的參數是錯誤的。包裹應用程序組件的路由器組件:

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

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