简体   繁体   中英

React Router works only after refreshing the page

I am a bit new to react and I am facing a problem with the Router. The routing works when I enter the URL directly on the browser, however when I click on the link, the URL changes on the browser (eg http://localhost:8080/contactus), but the content don't get updated (But if I do a refresh, it gets updated).

Here is my github repo: https://github.com/Arefaat18/Project

Here is my 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);

And here is my App.js file

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;

and here is the relevant dependancies

"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",

And here is my ContactUsComponent, the other components are just the same with different text

import React, { Component } from 'react';

class ContactUs extends Component {

    render(){
        console.log("RENDER");
        return (
            <div>
                <h1> Contact Us</h1>
            </div>
        );
    }
}

export default ContactUs;

Thanks in advance.

Right, you've extraneous Router s declared, your header component has one. Remove this Router .

It is because each Router provides a routing context, and each component subscribing to a routing context gets the context from the closest router. The router providing context to the header wasn't rendering any routes so that is why the URL would change but the router actually rendering the Route s wasn't being notified that it should render a different path.

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>
    );
  }
}

编辑 react-router-works-only-after-refreshing-the-page

I ran into a similar problem. I used Link in the components, but I imported it from @reach/router . As a result, I replaced

import { Link } from "@reach/router"

with

import { Link } from "react-router-dom"

in each component; and everything worked as it should

I just finish the course Front-End Web Development with React. I think you are learning this course too so I see nothing wrong with your code, possibly the problem is inside your ContactUs component. If you can provide your ContactUs code then I can debug it

I had the same issue as well but I had to wrap my App.js with BrowseRouter in the index.js file.

import {BrowserRouter as Router} from 'react-router-dom'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Router>
    <App />
  </Router>
);

Well I also stuck with the same Issue but in react 18 our component in index.js file is by default wrapped in react strict mode

like this:

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

I removed React strict Mode tags then it worked perfectly fine for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM