反应挂钩,将函数的返回值设置为状态会导致无限循环

时间:2020-02-11 09:01:45

标签: javascript reactjs react-hooks infinite-loop

设置状态的无限循环

我有一个对象数组testData,但我想过滤槽以得到另一个结果数组:

  const testData = [
    {
      time: "2020-01-23T13:16:53+01:00",
      amount: "0.010000000000000000",
      txid: "7b1f6aa63910618913c1c1c2902671d2e4f074a8c77ecfd3d16994a05fbf952d"
    },
    {
      time: "2020-01-31T09:09:13+01:00",
      amount: "-0.012739560000000000",
      txid: "7df38cb2d7538f794d725e4c7e68a3e1e7ee6fd570c3575c53776808c0200145"
    },
    {
      time: "2020-01-31T09:09:24+01:00",
      amount: "0.010000000000000000",
      txid: "db47ba29a36bd2343af287bd75f489c2f39d7ce1edcf24176c555233b0e24286"
    }
  ];

下面的代码几乎可以正常工作,但是我无法将返回值设置为一种状态。 当我尝试在函数中使用useState时,它给了我无限循环。我该如何设置historyResult()的状态返回值,所以每次值更改函数都会调用并给我不同的结果。

import React, { useState, useEffect } from 'react';

  const History = () => {
    const [filteredArray, setFilteredArray] = useState();

      // values are coming from Formik. When changed, function should run once more.
      const historyResult = values => {
        let tType = values && values.transactionType; // Checking if the value exists, saving transactionType of values and saving it to variable
        // testData is an array of objects that i want to filter trough
        let filteredData = testData.filter(item => {
          const withdraw = item.amount < 0;
          const admission = item.amount > 0;
          // Checking wich tType was returned and do instructions
          const type = tType == 1 ? withdraw : tType == 2 ? admission : console.log('no value');
          return type;
        });
        console.log(filteredData); // This log works beautifully - it gives me data i want (array of objects)
        setFilteredArray(filteredData); // I tried to set state on this but got infinite loop. Why's that?
        return filteredData;
      };
  }

  1. 如何将historyResult的返回值设置为没有无限循环的状态?
  2. 我尝试了useEffect,但我认为我全都弄错了,并且也遇到了无限循环。

1 个答案:

答案 0 :(得分:4)

  1. 您可以使用:

setFilteredArray([...filteredData]);

还用初始值初始化状态,例如空数组

const [filteredArray, setFilteredArray] = useState([]);

您不需要返回一个函数值。您从不在React世界中这样做,相反,您只是将状态设置为所需的结果并在所需的位置使用该状态。 (请注意,设置状态是异步调用)

  1. useEffect中无限循环的原因:
每次组件状态更改时,

useEffect都会调用,并且状态再次更改时,useEffect会被调用,并且此循环继续。这是很好的guide,可以防止useEffect中的无限循环