【问题标题】:React-router-dom v4 not rendering component on page loadReact-router-dom v4 在页面加载时不渲染组件
【发布时间】:2018-12-06 16:40:31
【问题描述】:

所以基本上我有一个导航栏,可以在路线之间切换。当页面加载时,默认情况下它会转到 /home 但实际上并没有呈现它所提供的 App 组件。我必须单击将您带到 /home 的按钮才能渲染它。

我在 Redux 中使用 react-router-dom。

这是我的浏览器路由器:

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

有什么建议吗?

【问题讨论】:

  • 发布完整的组件代码。 App是如何导入的? App.js 长什么样子?

标签: javascript reactjs redux react-router-v4 react-router-dom


【解决方案1】:

默认路由是/ 而不是/home。 您需要设置重定向。

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

【讨论】:

  • OP 说When the page loads, it goes to /home by default
【解决方案2】:

将您的/home 路由与所有其他路由放在Switch 中:

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

【讨论】:

  • 这是有道理的,但应用仍然无法在加载时呈现
【解决方案3】:

你需要把/home放在&lt;Switch&gt;里面

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

表示放在&lt;Switch&gt;中的代码行上方 例如:-

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

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 2022-07-28
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 2022-12-17
    • 1970-01-01
    相关资源
    最近更新 更多