简体   繁体   English

嵌套钩子与 useEffect 反应

[英]Nested hooks in react with useEffect

I have a component where I return all products from a specified category and return the data for each product.我有一个组件,我在其中返回指定类别的所有产品并返回每个产品的数据。 I get all products using:我使用以下所有产品:

  const [products, setProducts] = useState([]);
  // Get all of the available products from category
  useEffect(() => {
    fetch(state.source.api + "/cocart/v1/products?category=" + category.name)
      .then((response) => response.json())
      .then((data) => {
        setProducts(data);
      });
  }, []);

And display like:并显示如下:

<>
  {products.map(
    ({ id, name, price, categories, _links }) => {
      return (
        <>
          <p>{name}</p>

          <div>
            {_links.variations.map((item) => {
              return (
                <p>{item.href}</p>
              )
            })}
          </div>
        </>
      );
    }
  )}
</>

Each product also has 10 variations, though.不过,每种产品也有 10 种变体。 So within each product, I have to then fetch the data from each variation's api endpoint - which is the href.因此,在每个产品中,我必须从每个变体的 api 端点获取数据 - 即 href。

So ultimately, I am thinking that I need to create a second useEffect that will map through each variation of each product, and return the endpoint, THEN fetch that endpoint to return the endpoint's data.所以最终,我想我需要创建第二个 useEffect 来映射每个产品的每个变体,并返回端点,然后获取该端点以返回端点的数据。

I am completely at a standstill as to how to start this.我完全不知道如何开始。 Any help would be appreciated.任何帮助,将不胜感激。

Create new component with props variation .使用 props variation创建新组件。 This component gets variation and makes request.该组件获得变化并提出请求。

const Variation = ({ variation }) => {
  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    fetch(variation)
      .then(res => res.json())
      .then(setData)
      .catch(console.error);
  }, [variation]);

  return <p>{variation}</p>
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM