我是新手,仍在学习。我正在尝试在我的反应项目中添加嵌套路由,以便div 的内容根据路由进行更改。
以下是我的组件:-
//index.js
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
library.add(faIgloo);
ReactDOM.render(<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById('root'));
serviceWorker.unregister();
// app.js
import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import Login from './components/login/login.js'
import Protected from './components/protected/protected.js'
import './App.css';
class App extends Component {
render() {
return (
<Switch>
<Route exact path="/protected" component={Protected}/>
<Route path="/login" component={Login}/>
</Switch>
);
}
}
export default App;
//protected.js
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import Header from './header/header.js';
import './protected.css';
import CafePreview from './cafepreview/cafepreview.js'
class Protected extends Component {
render() {
const {match} = this.props;
return (
<div>
<Header></Header>
{/*<Preview/>*/}
<Switch>
<Route path='/protected/cafepreview' component={CafePreview}/>
</Switch>
</div>
);
}
}
export default Protected
// cafepreview.js
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import './preview.css';
console.log("here");
class CafePreview extends Component {
render() {
return (
<div>
<div>
<i class="fa fas fa-arrow-left"></i>
<span> BACK TO ALL CAFES </span>
</div>
</div>
);
}
}
export default CafePreview
当我打开"/protected"时,我可以看到标题,但是当我尝试打开"/protected/cafepreview"时,我看到一个空白页面,而不是带有咖啡馆预览html的标题。
我尝试了 react-router-dom v4 中此堆栈溢出线程多个嵌套路由中提到的一些选项,但没有一个有效。
我希望我已经清楚地解释了我的问题。
https://reacttraining.com/react-router/web/api/Route/exact-bool 检查文档。从 App 组件中的路由中删除exact
,它将开始工作。
这是因为您在app.js
文件中设置了exact
。将其从特定路由中删除。它会工作