【问题标题】:React conditional based on URL基于 URL 的条件反应
【发布时间】:2020-12-08 11:37:58
【问题描述】:

我有一个navbar 和一个联系按钮。我想根据 URL 将这个 Contact 按钮更改为 Back 按钮。

如果 url 是 localhost:5000/ 则设为 Contact,如果 url 是 localhost:5000/about 则应为 Back

这可能吗?我不确定哪种语法可以做到这一点。

{localhost:5000/ && <button>Contact</button>}

{localhost:5000/about && <button>Back</button>}

这显然是不正确的,我只是想知道是否有类似的方法。

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

如果您使用v5.1react-router 之后的版本,您可以选择在功能组件中使用useLocation 挂钩。这将有助于确定用户当前所在的路径 - 然后您可以评估是呈现“返回”还是“联系”。我建议为此使用三元运算符。

import { Route, useLocation, Link } from "react-router-dom";

export default function App() {
  const location = useLocation();

  return (
    <>
      ...
      
      {location.pathname === "/" ? <Link to="/contact">Contact</Link> : <Link to="/">Back</Link>}<br/>

      ...
    </>
  );
}

代码沙盒:https://codesandbox.io/s/infallible-williamson-489gl?file=/src/App.js


如果您使用较低版本的react-router 或使用基于类的组件,则可以使用withRouter。逻辑将非常相似,因为您将可以访问您的 location 对象,但 withRouter 是一个高阶组件

【讨论】:

    【解决方案2】:

    您需要为此使用react-router(显然您可以使用窗口对象)。但是 react router 更好:

    import React from 'react';
    import { withRouter } from "react-router";
    
    const Navbar = ({ location }) => {
     
       if (location.pathname.includes("about")) {
          // you can check using equality also (location.pathname === "/about")
           return <button>Back</button>
       }
    
       return <button>Contact</button>;
       
    }
    
    export default withRouter(Navbar);
    

    注意:只有 withRouter 如果您的组件无法访问响应路由器道具,否则如果它可以访问位置道具,则它可以在没有它的情况下工作

    【讨论】:

      【解决方案3】:

      假设Navbar组件可以访问路由器的props,你可以这样做:

      // ./components/Navbar.js
      import React from 'react';
      
      function Navbar({ location }) {
       
         if (location.pathname === "/about") {
             return <button>Back</button>
         }
      
         return <button>Contact</button>;
         
      }
      
      export default Navbar;
      

      如果您使用的 React 版本是 16.8 或更高版本,请考虑使用 Hook:

      // ./components/Navbar.js
      import React from 'react';
      import { useLocation } from 'react-router-dom';
      
      function Navbar({ location }) {
      
         let location = useLocation();
       
         if (location.pathname === "/about") {
             return <button>Back</button>
         }
      
         return <button>Contact</button>;
         
      }
      
      export default Navbar;
      

      【讨论】:

        猜你喜欢
        • 2019-08-04
        • 2012-09-11
        • 2016-08-16
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 2023-02-17
        相关资源
        最近更新 更多