繁体   English   中英

React hooks,将函数的返回值设置为 state 会导致无限循环

[英]React hooks, set return value of a function to state causes 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. 您可以使用:

setFilteredArray([...filteredData]);

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

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

您不需要从函数返回值。 在 React 世界中,您永远不会这样做,而只是状态设置为所需的结果并在您想要的地方使用该状态。 (请记住,设置状态是一个异步调用)

  1. useEffect无限循环的useEffect

useEffect调用每一个组件状态发生变化时,每当状态再次改变useEffect获取呼叫,这个周期继续。 这是防止useEffect无限循环的好指南

暂无
暂无

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

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