usecontext的有条件渲染

发布于 2025-01-20 19:33:46 字数 2186 浏览 1 评论 0原文

该任务要求我根据目标类别组从 API 获取数据。

例如,www.localhost:8000/women 会获取女性对应的所有数据,www.localhost:8000/women 会获取男性对应的所有数据。

我现在创建了一个通用的 ContextProvider,其中根据值获取数据。

为了更清楚起见,请查找下面的代码。

export const ProductCategoryContext = createContext();

const ProductCategoryContextProvider = ({ children }) => {
  const [products, setProducts] = useState([]);

//conditional value which must be updated in onClick function of a <Link>.
  const [targetGroup, setTargetGroup] = useState("");

  const URL = `${process.env.REACT_APP_HOST}`;

  async function getproducts() {
    console.log(targetGroup);
    console.log(123);
    try {
      if (targetGroup === "women") {
        const womensData = await fetch(`${URL}/women`);
        const jsonData = await womensData.json();
        console.log(jsonData?.items);
        setProducts(jsonData?.items);
      } else if (targetGroup === "men") {
        console.log(targetGroup);
        const mensData = await fetch(`${URL}/men`);
        const jsonData = await mensData.json();
        console.log(jsonData?.items);
        setProducts(jsonData?.items);
      }
    } catch (error) {
      console.error(error);
    }
  }

  useEffect(() => {
    getproducts();
  }, []);

  return (
    <ProductCategoryContext.Provider
      value={{
        product: products,
        targetGroup: targetGroup,
        setTargetGroup: setTargetGroup,
      }}
    >
      {children}
    </ProductCategoryContext.Provider>
  );
};

事件处理程序的代码如下:

  const { setTargetGroup } = useContext(ProductCategoryContext);

 return (<Link
          onClick={() =>  setTargetGroup("women")}
          className="category-links"
          to="/create/women"
        >
          <div className="card">
            <div className="card_image">
              <img
                className="category-images"
                src={require("../../assets/images/women-tile-image.jpg")}
                alt="image for womens section"
              />
            </div>
          </div>
        </Link>)

现在,targetGroup 的值仍未更新,因此我无法获取数据。我很困惑可能是什么问题?

The task requires me to fetch data from an API, based on target category groups.

For example, www.localhost:8000/women fetches all data corresponding to women, and www.localhost:8000/women fetch all data corresponding to men.

I have now created a common ContextProvider where data is fetched based on a value.

Please find the code below for better clarity.

export const ProductCategoryContext = createContext();

const ProductCategoryContextProvider = ({ children }) => {
  const [products, setProducts] = useState([]);

//conditional value which must be updated in onClick function of a <Link>.
  const [targetGroup, setTargetGroup] = useState("");

  const URL = `${process.env.REACT_APP_HOST}`;

  async function getproducts() {
    console.log(targetGroup);
    console.log(123);
    try {
      if (targetGroup === "women") {
        const womensData = await fetch(`${URL}/women`);
        const jsonData = await womensData.json();
        console.log(jsonData?.items);
        setProducts(jsonData?.items);
      } else if (targetGroup === "men") {
        console.log(targetGroup);
        const mensData = await fetch(`${URL}/men`);
        const jsonData = await mensData.json();
        console.log(jsonData?.items);
        setProducts(jsonData?.items);
      }
    } catch (error) {
      console.error(error);
    }
  }

  useEffect(() => {
    getproducts();
  }, []);

  return (
    <ProductCategoryContext.Provider
      value={{
        product: products,
        targetGroup: targetGroup,
        setTargetGroup: setTargetGroup,
      }}
    >
      {children}
    </ProductCategoryContext.Provider>
  );
};

The code for the event handler is as below:

  const { setTargetGroup } = useContext(ProductCategoryContext);

 return (<Link
          onClick={() =>  setTargetGroup("women")}
          className="category-links"
          to="/create/women"
        >
          <div className="card">
            <div className="card_image">
              <img
                className="category-images"
                src={require("../../assets/images/women-tile-image.jpg")}
                alt="image for womens section"
              />
            </div>
          </div>
        </Link>)

Now, the value of targetGroup remained unupdated because of which I am unable to fetch the data. I'm confused about what the problem could be?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自此以后,行同陌路 2025-01-27 19:33:46

据我所见,useEffect 钩子缺少对引用的 targetGroup 状态值的依赖。空的依赖数组告诉 React 在初始渲染时运行一次效果。由于 targetGroup 初始状态值为 "",因此不会提取任何内容,因此效果不会“侦听”任何依赖项更改为可能重新提取。

targetGroup 添加到 useEffect 挂钩的依赖项数组中,以便在更新时触发效果回调。将 URLgetproducts 移动到 useEffect 回调正文中,以将它们作为依赖项删除。

const ProductCategoryContextProvider = ({ children }) => {
  const [products, setProducts] = useState([]);

  //conditional value which must be updated in onClick function of a <Link>.
  const [targetGroup, setTargetGroup] = useState("");

  useEffect(() => {
    const URL = `${process.env.REACT_APP_HOST}`;

    async function getproducts() {
      try {
        if (targetGroup === "women") {
          const womensData = await fetch(`${URL}/women`);
          const jsonData = await womensData.json();
          setProducts(jsonData?.items);
        } else if (targetGroup === "men") {
          const mensData = await fetch(`${URL}/men`);
          const jsonData = await mensData.json();
          setProducts(jsonData?.items);
        }
      } catch (error) {
        console.error(error);
      }
    };

    getproducts();
  }, [targetGroup]); // <-- add targetGroup as dependency

  return (
    <ProductCategoryContext.Provider
      value={{
        product: products,
        targetGroup: targetGroup,
        setTargetGroup: setTargetGroup,
      }}
    >
      {children}
    </ProductCategoryContext.Provider>
  );
};

您可能还会发现为 React hook 添加 ESLint 插件 很有帮助。它将帮助您解决缺少依赖项和其他常见的 React hook 问题。

From what I can see, the useEffect hook is missing a dependency on the referenced targetGroup state value. The empty dependency array tells React to run the effect once on the initial render. Since the targetGroup initial state value is "" nothing is fetched and then the effect isn't "listening" for any dependency to change to possibly refetch.

Add targetGroup to the useEffect hook's dependency array so when it updates the effect callback is triggered. Move URL and getproducts into the useEffect callback body to remove them as dependencies.

const ProductCategoryContextProvider = ({ children }) => {
  const [products, setProducts] = useState([]);

  //conditional value which must be updated in onClick function of a <Link>.
  const [targetGroup, setTargetGroup] = useState("");

  useEffect(() => {
    const URL = `${process.env.REACT_APP_HOST}`;

    async function getproducts() {
      try {
        if (targetGroup === "women") {
          const womensData = await fetch(`${URL}/women`);
          const jsonData = await womensData.json();
          setProducts(jsonData?.items);
        } else if (targetGroup === "men") {
          const mensData = await fetch(`${URL}/men`);
          const jsonData = await mensData.json();
          setProducts(jsonData?.items);
        }
      } catch (error) {
        console.error(error);
      }
    };

    getproducts();
  }, [targetGroup]); // <-- add targetGroup as dependency

  return (
    <ProductCategoryContext.Provider
      value={{
        product: products,
        targetGroup: targetGroup,
        setTargetGroup: setTargetGroup,
      }}
    >
      {children}
    </ProductCategoryContext.Provider>
  );
};

You may also find adding the ESLint plugin for React hooks helpful. It will help you with missing dependencies and other general React hook issues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文