在我的家庭课堂中,我有一个Hello,每次更改标签时,Hello总是被渲染。我该如何预防?我没有在其他选项卡中包括Hello的任何字段,这很奇怪。
import React, { Component } from 'react';
export default class Home extends Component {
constructor(props) {
super(props);
}
render() {
return (
<h3>Hello</h3>
)
}
}
import "bootstrap/dist/css/bootstrap.min.css";
import {BrowserRouter as Router,Route,} from 'react-router-dom'
import NotFound from './components/App/NotFound';
import Home from './components/Home/Home';
import Navbar from "./components/NavBar/Navbar";
import Login from "./components/Login/Login";
import SignUp from "./components/SignUp/SignUp";
function App() {
return (
<Router>
<div className="container">
<Navbar />
<br/>
<Route path="/" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/signup" component={SignUp}/>
</div>
</Router>
);
}
export default App;
react应用的图片,
答案 0 :(得分:1)
嘿,你可能想这样做
<Route path="/" exact={true} component={Home}/>
路径/
实际上与网站上的所有内容都匹配,以防止您可以使用它,
exact
prop <Route path="/" exact={true} component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/signup" component={SignUp}/>
Switch
component <Switch>
<Route path="/" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/signup" component={SignUp}/>
</Switch>
将仅使用一个Route
。注意:您必须保持订单不变
答案 1 :(得分:0)
发生这种情况的原因是,您将所有路线都渲染在一起。您应该为每个路线在路线组件中传递exact
道具
<Route exact path="/signup" component={SignUp}/>
或在Switch
标签内呈现您的路线。
<Switch>
<Route path="/" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/signup" component={SignUp}/>
</Switch>
请记住,路由的顺序也很重要,您可能希望在最后显示根路由。对于后者,不要忘记从react-router-dom
导入Switch