我有一个反应应用程序。
我有组件路由问题
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from './app';
ReactDOM.render(
<App/>,
document.getElementById("root")
);
app.jsx
我在这里路由2个组件。登录和主要组件。在主要组件中有许多将用于仪表板的路由器。
我的问题:在<Switch>
第一个<Route>
可以渲染,但如果我在网址硬编码它不会从第二个路由器渲染
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Switch
} from 'react-router-dom';
import Login from './login';
import Main from './main';
import createBrowserHistory from 'history/createBrowserHistory';
const customHistory = createBrowserHistory();
class App extends Component {
constructor(props) {
super(props);
window.token = '';
}
render() {
return <div>
<Router>
<Switch>
<Route to="/login" component={Login} exact />
<Route to="/main" component={Main} exact/>
</Switch>
</Router>
</div>;
}
}
export default App;
main.jsx
import React, {Component} from 'react';
import ReactDOM from "react-dom";
import { HashRouter, Route, Switch } from "react-router-dom";
import indexRoutes from "routes/index.jsx";
import "bootstrap/dist/css/bootstrap.min.css";
import "./assets/css/animate.min.css";
import "./assets/sass/light-bootstrap-dashboard.css?v=1.2.0";
import "./assets/css/demo.css";
import "./assets/css/pe-icon-7-stroke.css";
import Login from './login';
class Main extends Component {
constructor(props) {
super(props);
}
render() {
return <HashRouter>
<Switch>
{indexRoutes.map((prop, key) => {
return <Route to={prop.path} component={prop.component} key={key} />;
})}
</Switch>
</HashRouter>;
}
}
export default Main;
使用
<Route path="/login" component={Login} exact />
而不是to
使用path
<Route path="/login" component={Login} />
<Route path="/main" component={Main} exact/>
使用路径代替To
不要在主路线中使用精确属性,如下所示。
class App extends Component {
render() {
return <div>
<Router>
<Switch>
...
<Route to="/main" component={Main} />
</Switch>
</Router>
</div>;
}
}