Reaction路由器仅在刷新页面后才起作用
我的反应有点新手,我面临着路由器的问题。 当我直接在浏览器上输入网址时,路径选择会起作用,但是当我点击链接时,网址会在浏览器上改变(例如,http://localhost:8080/contactus),,但内容不会更新(但如果我刷新,它就会更新)。
这是我的GitHub回购: https://github.com/Arefaat18/Project
这是我的MainComponent.js
import React, { Component } from 'react';
import {TransitionGroup, CSSTransition} from 'react-transition-group';
import {Switch, Route, Redirect,withRouter,BrowserRouter as Router} from 'react-router-dom';
import Header from './HeaderComponent';
import ContactUs from './ContactUsComponent';
import AboutUs from './AboutUsComponent';
import Home from './HomeComponent.js';
import {connect} from 'react-redux';
class Main extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Router>
<Header />
<TransitionGroup>
<CSSTransition classNames="page" timeout={300}>
<Switch>
<Route path="/home" component={Home} />
<Route exact path = "/contactus" component ={ContactUs} />
<Route exact path = "/aboutus" component ={AboutUs} />
<Redirect to="/home" />
</Switch>
</CSSTransition>
</TransitionGroup>
</Router>
</div>
);
}
}
export default withRouter(Main);
这是我的App.js文件
import React, { Component } from 'react';
import Main from './components/MainComponent';
import './App.css';
import {BrowserRouter} from 'react-router-dom';
import {Provider} from 'react-redux';
import {ConfigureStore} from './components/configureStore';
const store = ConfigureStore();
class App extends Component {
render() {
return (
<Provider store={store}>
<BrowserRouter>
<div className="App">
<Main />
</div>
</BrowserRouter>
</Provider>
);
}
}
export default App;
这里是相关的受抚养人
"react": "^17.0.1",
"react-bootstrap": "^1.4.0",
"react-dom": "^17.0.1",
"react-redux": "^7.2.1",
"react-redux-form": "^1.16.14",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.4",
这是我的ContactUsComponent,其他组件是相同的,不同的文本
import React, { Component } from 'react';
class ContactUs extends Component {
render(){
console.log("RENDER");
return (
<div>
<h1> Contact Us</h1>
</div>
);
}
}
export default ContactUs;
提前谢谢。
解决方案
对,您声明了无关的Router
%s,您的头组件有一个。删除此Router
。
这是因为每个Router
都提供一个路由上下文,而订阅一个路由上下文的每个组件都从最近的路由器获取上下文。为标头提供上下文的路由器未呈现任何路由,因此URL将更改,但呈现Route
%s的路由器实际上未收到应呈现其他路径的通知。
class Header extends Component {
constructor(props) {
...
}
...
render() {
return (
<React.Fragment>
{/* <Router> */} // <-- Remove this Router Component
<Navbar dark expand="md">
...
</Navbar>
<Modal isOpen={this.state.isModalOpen} toggle={this.toggleModal}>
...
</Modal>
{/* </Router> */}
</React.Fragment>
);
}
}
相关文章