gpt4 book ai didi

javascript - React Router 仅在刷新页面后才起作用

转载 作者:行者123 更新时间:2023-12-05 08:37:46 26 4
gpt4 key购买 nike

我对 react 有点陌生,我正面临路由器问题。当我直接在浏览器上输入 URL 时路由有效,但是当我单击链接时,浏览器上的 URL 会发生变化(例如 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;

提前致谢。

最佳答案

好吧,我也遇到了同样的问题,但在 React 18 中,我们在 index.js 文件中的组件默认包装在 React Strict 模式下

像这样:

<React.StrictMode>
<App/>
</React.StrictMode>

我删除了 React strict Mode 标签,然后它对我来说工作得很好

关于javascript - React Router 仅在刷新页面后才起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64530117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com