【问题标题】:React - How render a component only on some exact route path?React - 如何仅在某些确切的路由路径上渲染组件?
【发布时间】:2019-12-14 15:17:06
【问题描述】:

我是 react 的初学者,但我还有一个我无法解决的问题: 我想在除 Home 之外的每个路由组件中渲染一个 <NavBar/>。我有以下无法解决任何问题的代码:

const App = props => {

  function getBar() {
    if(props.location === "/"){
      return <NavBar/>
    }
  };

  return (
    <Router>
      <div className="App">
        {getBar()}
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/feed" component={Feed} />
          <Route path="/profile" component={Profile} />
          <Route path="/newPost" component={NewPost}/>
        </Switch>   
      </div>
    </Router>
  );
}

【问题讨论】:

    标签: reactjs if-statement routes react-router


    【解决方案1】:

    您可以使用pathname:

    if (props.location.pathname === "/") {
    

    或创建一个新的Route 并准确指定您希望它呈现的位置:

    <Route path={['/feed', '/profile', ...]} exact component={Navbar} />
    

    注意:记得把它放在Switch之外。

    【讨论】:

    • 用户好。谢谢您的回答!第二个解决方案有效,但不是第一个。我在 getBar() 函数中做错了什么?
    • 导航栏不在任何路径中呈现。
    • @PedroRelvas 添加console.log(props.location) 并告诉我
    • 它返回“未定义”。
    • @PedroRelvas 使用 HOC withRouter 包裹您的 App 组件或改用 window.location.pathname
    【解决方案2】:

    替换

    {getBar()}
    

    {window.location.pathname !== "/" && getBar()}
    

    【讨论】:

      猜你喜欢
      • 2022-08-02
      • 2017-09-30
      • 2022-01-21
      • 2019-07-22
      • 2020-03-11
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多