useEffect导致无限循环

时间:2020-06-02 00:48:52

标签: reactjs react-hooks infinite-loop use-effect use-state

我已经查看了SO中的每个无限循环答案,但无法弄清楚自己在做什么错。

我正在尝试获取一些数据并使用数据设置我的productList状态,但这会导致无限循环。

export default (props) => {
  const [productsList, setProductsList] = useState([]);

  const getProducts = async () => {
    try {
      await axios
        .get("https://api.stripe.com/v1/skus", {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${StripeKey}`,
          },
        })
        .then(({ data }) => {
          setProductsList(data.data);
        });
    } catch {
      (error) => {
        console.log(error);
      };
    }
  };

  useEffect(() => {
    getProducts();
  }, [productList]);

  return (
    <ProductsContext.Provider value={{ products: productsList }}>
      {props.children}
    </ProductsContext.Provider>
  );
};

我还尝试过在useEffect的末尾使用一个空数组,这将导致它根本不设置状态。

我想念什么?

编辑:

我从useEffect中删除了try / catch和[productList]

import React, { useState, useEffect } from "react";
import axios from "axios";

const StripeKey = "TEST_KEY";

export const ProductsContext = React.createContext({ products: [] });

export default (props) => {
  const [productsList, setProductsList] = useState([]);

  useEffect(() => {
    axios({
      method: "get",
      url: "https://api.stripe.com/v1/skus",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${StripeKey}`,
      },
    })
      .then((response) => {
        setProductsList(response.data.data)
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return (
    <ProductsContext.Provider value={{ products: productsList }}>
      {props.children}
    </ProductsContext.Provider>
  );
};

1 个答案:

答案 0 :(得分:1)

关于如何获取数据: 我认为问题可能出在您如何获取数据上:

docs中所述,我认为您不应该在此处使用try catch,而是类似:

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  // Note: the empty deps array [] means
  // this useEffect will run once
  // similar to componentDidMount()
  useEffect(() => {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result.items);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map(item => (
          <li key={item.name}>
            {item.name} {item.price}
          </li>
        ))}
      </ul>
    );
  }
}

关于useEffect回调:

我认为您不应该将[productList]用作要更新的项目,因此一旦执行setProducts它将再次触发。您可能想在请求的属性更改或仅在组件上挂载时再次进行获取(如您所说的空数组)

此外,使用该代码示例可能看不到其他副作用。也许您可以共享一个堆栈闪电来确保