在导航栏中反应路由器动态链接

时间:2021-06-28 13:42:19

标签: reactjs react-router-dom

我正在尝试构建一个导航栏,其中链接根据 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 的新手,如果这是一个愚蠢的问题,请提前道歉!

3 个答案:

答案 0 :(得分:0)

您可以使用 react-router-dom's 钩子中的 pathname useLocation

import { useLocation } from "react-router-dom"

// 
const { pathname } = useLocation();

const Component = () => {

    return (
        {pathname === '/SavedRecipes' ? (
        ....
        )}
    );
}

答案 1 :(得分:0)

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

  const pathnameIsSavedRecipes =  window.location.pathname === '/SavedRecipes'

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

答案 2 :(得分:0)

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

yarn add react-router

然后在“路由”内的 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