问题描述
ReactJS路由器不会刷新组件,除非刷新,即使我创建了一个具有相同安装的不同项目,它也能正常工作,但在我当前的项目中却没有。
App.js
import React,{Component} from 'react';
import { browserRouter,Route,Switch} from 'react-router-dom';
import Navigation from './components/Navigation'
import Home from './components/Home'
import Blogs from './components/Blogs'
import Footer from './components/Footer'
import Services from './components/Services'
class App extends Component {
render(){
return (
<browserRouter>
<div className='grid-container'>
<Navigation />
<div className='content'>
<Route path='/blogs' component={Blogs} />
<Route path='/' component={Home} exact/>
<Route path='/' component={Services}/>
</div>
<Footer />
</div>
</browserRouter>
);
}
}
export default App;
Home.js
import React from 'react';
import {Link,browserRouter} from 'react-router-dom'
const Home = () => {
return (
<browserRouter>
<section className="carousel-section-wrapper home">
<div className="carousel-inner">
<div className="carousel-section carousel-item active clip-bg pt-225 pb-200 img-bg">
<div className="container">
<div className="row">
<div className="col-xl-8 col-lg-10 mx-auto">
<div className="carousel-content text-center">
<div className="section-title">
<h2>test content</h2>
<p className="text-white">test content</p>
</div>
<Link to="/blogs" className="theme-btn">Read My Blogs</Link>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</browserRouter>
)
}
export default Home
Blogs.js
import React from 'react';
const Blogs = () => {
return (
<h1>Blogs</h1>
)
}
export default Blogs
预期结果:当我单击任何按钮重定向到/ blogs时,组件首页和服务消失,并且出现博客组件
实际结果:除非刷新浏览器,否则页面状态保持不变
您的帮助将不胜感激。
解决方法
您已在嵌套组件,App和Home组件中使用了BrowserRouter
,但这种方式无法正常工作。要解决此问题,您只需在应用程序组件中安装BrowserRouter
。