我正在构建一个食谱应用程序,我为主页构建的组件在每个其他路由(或页面)上渲染。我将单击转到我构建的随机配方组件,您瞧,我的主页组件呈现在它下面。这是我所有的路由的情况。
我怎样才能使主页组件不会在每个其他页面上呈现?
import React from 'react';
import hero from './cuttingboard.jpg';
import cooking from './random.jpeg';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import {Link } from 'react-router-dom'
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
return (
<div className="homepage">
<div className="hero">
<img className="cuttingboard" src={hero}></img>
<h1>Find recipes</h1>
<div className="hero-p">
<h3>Lorem, ipsum dolor.</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, recusandae voluptatem ullam commodi perspiciatis, quod libero totam esse odio voluptas culpa dolore cum molestiae voluptates tempore, numquam corrupti ipsum similique.</p>
</div>
</div>
<div className="hero-features">
<h1>Browse recipes to your hearts' extent</h1>
</div>
<div className="home-random">
<img src={cooking}></img>
<Link to='/random'>
<h1>Get random meal</h1>
</Link>
</div>
</div>
)
}
}
export default Home;
import React from 'react';
import './App.css';
import Nav from './Nav';
import Meals from './Meal';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import RandomRecipe from './RandomRecipe';
import Home from './Home'
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
return (
<Router>
<div className="content">
<Nav />
<Switch>
<Route path="/meals" exact component={Meals}/>
<Route path="/random" exact component={RandomRecipe}/>
</Switch>
</div>
<Home />
</Router>
);
}
}
export default App;
为什么不为Home组件定义单独的路由下面的代码将解决您的问题。Home组件会在每条路由上呈现,因为你没有像在其他组件中那样在路由中定义。快乐学习! !
<Router>
<div className="content">
<Nav />
<Switch>
<Route path="/meals" exact component={Meals}/>
<Route path="/random" exact component={RandomRecipe}/>
<Route path="/home" exact component={Home}/>
</Switch>
</div>
</Router>