【问题标题】:How to make a "global" component render content based on url route?如何使“全局”组件基于 url 路由呈现内容?
【发布时间】:2020-11-20 22:52:38
【问题描述】:

我有一个固定在屏幕右下角的常见问题解答按钮(它位于网站的每个屏幕上),单击时会弹出一个显示常见问题及其各自答案的模式,我希望该模式能够根据用户所在的 url 显示不同的内容。

例如:如果用户在 www.example.com/signup 上,则模式将呈现特定于注册过程的内容,并且当用户在 www.example.com/shop 上时> 只会出现与购物相关的常见问题。这应该考虑到 url 参数的 first 部分,因此如果用户转到 www.example.com/shop/294594(或任何其他带有 /shop 星号的路线),那么modal 仍然显示与 www.example.com/shop 相同的内容。

react-router(或任何其他替代方案)有什么好的方法吗?我对 react-router useParams hook 做了一些研究,但我不确定它是否是首选解决方案,因为我只是路由的初学者。感谢您的宝贵时间!

【问题讨论】:

  • 我认为你可以使用 react-router <Route>
  • 也可以使用&lt;Switch&gt;组件来渲染不同的基于路由的内容

标签: javascript reactjs react-router jsx react-router-dom


【解决方案1】:

你可以像https://codesandbox.io/s/react-router-tgh8c?file=/components/FAQ.js这样创建一个FAQ组件

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

const SignupFaq = () => <p>Sign up questions</p>;
const ShopFaq = () => <p>Shop questions</p>;

const faqs = {
  signup: {
    component: <SignupFaq />
  },
  shop: {
    component: <ShopFaq />
  }
};

function FAQ() {
  const { pathname } = useLocation();

  const { component } = faqs[pathname.split("/")[1]];

  const [modal, showModal] = React.useState(false);

  return (
    <React.Fragment>
      <button onClick={() => showModal(!modal)}>FAQ</button>
      <div className="modal">{modal && <div>{component}</div>}</div>
    </React.Fragment>
  );
}

export default FAQ;

【讨论】:

  • 谢谢!如果没有找到“默认”路由,我会在 faqs 对象中创建一个默认键并执行const { component } = faqs[pathname.split("/")[1]] ? faqs[pathname.split("/")[1]] : faqs.default;(当然最好在 const 中定义faqs[pathname.split("/")[1]] ,这样更具可读性)。使用 useLotation() 和 react-router,您的解决方案可以按预期完美运行。
猜你喜欢
  • 1970-01-01
  • 2016-12-26
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2021-09-11
  • 2017-11-09
  • 2016-10-10
相关资源
最近更新 更多