简体   繁体   中英

React-router-dom v4 not rendering component on page load

So basically I have a navbar that switches between routes. When the page loads, it goes to /home by default but doesn't actually render the App component it's being given. I have to click on the button that brings you to /home in order to render this.

I'm using react-router-dom with Redux.

Here's my BrowserRouter:

<Provider store = {store}>
    <BrowserRouter>
      <div>
        <Header />
        <Route exact path = "/home" component={App}> </Route>
        <Switch>
          <Route  path = "/about" render = {() => <AboutUs />}></Route>
          <Route  path = "/contact" render = {() => <Contact />}></Route>
          <Route  path = "/services" render = {() => <Services />}></Route>
        </Switch>
      </div>
    </BrowserRouter>
  </Provider>

Any advice?

The default route is / not /home . You need to setup a redirect.

<Route exact path="/" render={() => ( <Route exact path="/home" component={App} /> )} />

Put your /home route in the Switch with all the other routes:

<Provider store = {store}>
    <BrowserRouter>
      <div>
        <Header />
        <Switch>
          <Route exact path = "/home" component={App}> </Route>
          <Route  path = "/about" render = {() => <AboutUs />}></Route>
          <Route  path = "/contact" render = {() => <Contact />}></Route>
          <Route  path = "/services" render = {() => <Services />}></Route>
        </Switch>
      </div>
    </BrowserRouter>
  </Provider>

You need to put /home inside <Switch>

<Route exact path = "/home" component={App}> </Route>

Means put above line of code inside <Switch> ex:-

<Switch>
      <Route exact path = "/home" component={App}> </Route>
      <Route  path = "/about" render = {() => <AboutUs />}></Route>
      <Route  path = "/contact" render = {() => <Contact />}></Route>
      <Route  path = "/services" render = {() => <Services />}></Route>
</Switch>

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