【问题标题】:issue with how to render with react router关于如何使用反应路由器渲染的问题
【发布时间】:2019-03-16 22:16:24
【问题描述】:

我有这种特殊情况,如果用户路由说主题/渲染,我需要向他展示一个单独的组件,当用户路由到主题/10 时,我需要向他展示另一个组件。 我现在面临的问题是,即使我进行主题/渲染,我看到两个组件都在屏幕上渲染。 此外,当用户路由到主题/数学/10 时, 我需要将他引导到其他页面。

这是我的 App.js 中的路由部分(默认 App.js)

<div className="App">
    <Router>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route exact path="/topics" component={Topics} />
      <Route exact path ="/topics/rendering" component={Description}/>
      <Route  exact path="/topics/:id" component={Topic} />
      <Route path="/topics/:description/:id" component={TopicExtended}/>
    </Router>
  </div>

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您希望将 Route 组件包装在 Switch 组件中,以便一次只呈现其中一个。

<div className="App">
  <Router>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
      <Route path="/topics/rendering" component={Description} />
      <Route path="/topics/:id" component={Topic} />
      <Route path="/topics/:description/:id" component={TopicExtended} />
    </Switch>
  </Router>
</div>

【讨论】:

    【解决方案2】:

    你应该把 Route 标签放在 Switch 标签里面

    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/topics" component={Topics} />
        <Route path ="/topics/rendering" component={Description}/>
        <Route path="/topics/:id" component={Topic} />
        <Route path="/topics/:description/:id" component={TopicExtended}/>
      </Switch>
    </Router>
    

    但先导入import {Switch} from 'react-router-dom'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2020-04-09
      相关资源
      最近更新 更多