我试图在index.js文件中实现BroserRouter。但是我得到了错误。
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
const app = (<BrowserRouter>
<App />
</BrowserRouter>
);
ReactDOM.render( app, document.getElementById( 'root' ));
registerServiceWorker();
您需要将<App />
放置在<Switch></Switch>
中并作为<Route>
的属性。
不要忘记为其中一条路由使用exact
属性。(只是为你的主页像Index.js)
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch } from "react-router-dom";
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
const app = (<BrowserRouter>
<Switch>
<Route exact path="/" render={() => <App />} />
{/* Other routs: */}
<Route path="/Component2" render={() => <Component2 />} />
<Route path="/Component3" render={() => <Component3 />} />
</Switch>
</BrowserRouter>
);
ReactDOM.render(app, document.getElementById('root'));
registerServiceWorker();