React:避免使用设置默认值的 hooks,使用带默认值的 getters

发布: (2026年3月13日 GMT+8 18:49)
1 分钟阅读
原文: Dev.to

Source: Dev.to

问题

同事帮助发现了一个可能导致错误的模式。
当用户打开 mysite.com/?urlParam=foo 时,应用应加载对应的 FooComponent。如果网站在没有任何查询参数的情况下打开,也应默认加载 FooComponent

组件示例

export const MyAdvancedComponent = () => {
  useSetDefaultParameters();

  const { params } = usePlaygroundContext();

  return (
    <>
      {params.foo === "foo" && <FooComponent />}
      {params.foo === "bar" && <BarComponent />}
      {/* …other components */}
    </>
  );
};

Hook 实现

export const useSetDefaultParameters = () => {
  const urlParam = useGetUrlParam();

  const { setParam } = useMyContext();

  useEffect(() => {
    const defaultValue = defaults[urlParam];
    setParam(urlParam, defaultValue);
  }, [urlParam]);
};
0 浏览
Back to Blog

相关文章

阅读更多 »

我写了一本惊人的 React 书

《我写了一本惊人的 React 书》封面图片 https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-...