使用中的无限循环设置状态时的效果

时间:2019-10-20 11:07:10

标签: reactjs react-hooks

我里面有一个关于useEffectuseState的问题。 我正在构建一个组件:

const [id, setId] = useState(0);
const [currencies, setCurrencies] = useState([]);

...
useEffect(()=> {
const getCurrentCurrency = async () => {
            const response = await fetch(`https://api.exchangeratesapi.io/latest?base=GBP`);
            const data = await response.json();
            const currencyArray = [];
            const {EUR:euro ,CHF:franc, USD: dolar} = data.rates;
            currencyArray.push(euro, dolar/franc,1/dolar);
            console.log("currencyArray", currencyArray);
             setCurrencies(currencies => [...currencies, currencyArray]);
          }
          getCurrentCurrency();
    }, [id, currencies.length]);

仅当id更改时,哪个用于发出新的API请求。每当ID更改使用新数据提出新请求时,我都需要。就我而言,现在有无限循环。我尝试使用依赖项,但是它没有按预期工作。

4 个答案:

答案 0 :(得分:1)

您每次通话都更改currencies.length所依赖的值(useEffect[id, currencies.length])。

因此会导致无限循环。

useEffect(() => {
  const getCurrentCurrency = async () => {
    // ...
    currencyArray.push(euro, dolar / franc, 1 / dolar);

//                    v The length is changed on every call
    setCurrencies(currencies => [...currencies, currencyArray]);
  };
  getCurrentCurrency();
//                    v Will called on every length change
}, [id,currencies.length]);

使用功能性currencies.lengthuseState

时,不需要currencies => [...currencies, currencyArray]作为依赖项
useEffect(() => {
  const getCurrentCurrency = async () => {
    ...
  }
  getCurrentCurrency();

}, [id]);

此外,由于它似乎是一种交换应用程序,因此您可以使用一个间隔来获取货币:

useEffect(() => {
  const interval = setInterval(getCurrency, 5000);
  return () => clearInterval(interval);
}, []);

答案 1 :(得分:1)

您可以仅将useEffect cb称为安装的组件之一:

useEffect(()=>{
 //your code
 // no need for checking for the updates it they are inside the component
 }, []);

答案 2 :(得分:0)

我想仅在ID更改时才更改状态,而当我执行类似的操作时,货币更改之间就存在无限循环。我只想在使用useEfect装入DOM后初始化具有3个值的currency数组,然后在更新id时更改此数组。但是现在我开始时有无限循环。

const Slide = () => {
    const [id, setId] = useState(0);
    const [currencies, setCurrencies] = useState([]);

    //console.log("go: ", currencies);

    useEffect(()=> {

        const getCurrentCurrency = async () => {
            const response = await fetch(`https://api.exchangeratesapi.io/latest?base=GBP`);
            const data = await response.json();
            const currencyArray = [];
            const {EUR:euro ,CHF:franc, USD: dolar} = data.rates;
            currencyArray.push(euro, dolar/franc,1/dolar);
            console.log("currencyArray", currencyArray);

            //setCurrencies(currencyArray);

             setCurrencies(currencies => [...currencies, currencyArray]);

          // setCurrencies([euro,dolar/franc, 1/dolar]);
        }
        getCurrentCurrency();

    }, [id]);



    const goToPrevSlide = () => {
        id === 0 ? setId(2) : setId(id-1);
    }
    const goToNextSlide = () =>{
        id === 2 ? setId(0) : setId(id+1);
    }

答案 3 :(得分:0)

<?php echo do_shortcode('[mycred_link href="the_1_code_inside_here"]View portfolio[/mycred_link]'); ?>

为什么这个 const [id, setId] = useState(0); const [currencies, setCurrencies] = useState([]); const images = [ "https://images.pexels.com/photos/672532/pexels-photo-672532.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940", "https://images.pexels.com/photos/773471/pexels-photo-773471.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940", "https://images.pexels.com/photos/64271/queen-of-liberty-statue-of-liberty-new-york-liberty-statue-64271.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" ]; //console.log("go: ", currencies); useEffect(()=> { const getCurrentCurrency = async () => { const response = await fetch(`https://api.exchangeratesapi.io/latest?base=GBP`); const data = await response.json(); const {EUR:euro ,CHF:franc, USD: dolar} = data.rates; if(currencies.length == 0){ //setCurrencies(currencies => [...currencies, [euro, dolar/franc, 1/dolar]]); -> DIDN'T WORK //setCurrencies([euro, dolar/franc,1/dolar]); currencies.push(euro, dolar/franc,1/dolar); //hax this works } else{ currencies.splice(0, currencies.length, [euro, dolar/franc, 1/dolar]); //this works } console.log(currencies); } getCurrentCurrency(); }, [id]); 导致无限循环?有人可以解释我吗?