[英]React Hooks useCallback and useEffect causes infinite loop in react application
[英]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;
};
}
setFilteredArray([...filteredData]);
還用初始值初始化您的狀態,例如空數組
const [filteredArray, setFilteredArray] = useState([]);
您不需要從函數返回值。 在 React 世界中,您永遠不會這樣做,而只是將狀態設置為所需的結果並在您想要的地方使用該狀態。 (請記住,設置狀態是一個異步調用)
useEffect
無限循環的useEffect
: useEffect
調用每一個組件狀態發生變化時,每當狀態再次改變useEffect
獲取呼叫,這個周期繼續。 這是防止useEffect
無限循環的好指南
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.