【问题标题】:React Router Dynamic Links in Navbar导航栏中的 React Router 动态链接
【发布时间】:2021-06-28 22:01:47
【问题描述】:

我正在尝试构建一个导航栏,其中链接根据 window.location.pathname 更改。但是,当页面更改时,链接不会重新呈现。完成这项工作的最简单方法是什么?



          {window.location.pathname === '/SavedRecipes' ? (
            <Button
              onClick={() => setSearchQuery('')}
              color="inherit"
              to="/"
              component={RouterLink}
            >
              Search
            </Button>
          ) : (
            <Button
              onClick={() => setSearchQuery('')}
              color="inherit"
              to="/SavedRecipes"
              component={RouterLink}
            >
              Saved Recipes
              <BookmarkBorderIcon />
            </Button>
          )}

任何帮助都将不胜感激,因为我是 React 新手,如果这是一个愚蠢的问题,请提前道歉!

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    你可以从useLocation钩子中使用react-router-dom'spathname

    import { useLocation } from "react-router-dom"
    
    // 
    const { pathname } = useLocation();
    
    const Component = () => {
    
        return (
            {pathname === '/SavedRecipes' ? (
            ....
            )}
        );
    }
    

    【讨论】:

    • 非常感谢!我希望它会像这样简单!非常感谢!
    • @Wekiban 考虑接受答案,以便其他人也受益。
    【解决方案2】:

    你只能像这样使用一个按钮:

      const pathnameIsSavedRecipes =  window.location.pathname === '/SavedRecipes'
    
      <Button
        onClick={() => setSearchQuery("")}
        color="inherit"
        to={pathnameIsSavedRecipes ? "/" : "/SavedRecipes"}
        component={RouterLink}
      >
        {pathnameIsSavedRecipes ? "Search" :  "Saved Recipes"}
        {!pathnameIsSavedRecipes && <BookmarkBorderIcon />}
      </Button>
    

    【讨论】:

      【解决方案3】:

      如果你还没有使用“react-router”,你可以使用:

      yarn add react-router
      

      然后在“Route”内的 React.Component 中,您可以调用:

      this.props.location.pathname
      

      如果您使用的是 react 路由器,您可能会发现检查 useLocation 和 useHistory 挂钩很有用。两者都创建了一个具有路径名属性的对象,您可以阅读这些属性,并且对一堆其他东西很有用。这是一个 youtube 视频 [解释反应路由器挂钩][1]

      两者都会给你你需要的东西(没有域名):

      import { useHistory ,useLocation } from 'react-router-dom';
      const location = useLocation()
      location.pathname
      
      const history = useHistory()
      history.location.pathname
      

      【讨论】:

        猜你喜欢
        • 2017-09-08
        • 2021-11-28
        • 2019-09-06
        • 1970-01-01
        • 2021-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-30
        相关资源
        最近更新 更多