const DataManipulation = ({ data }) => {
const [taskData, setTaskData] = useState([]);
const subItemMaker = (subItem, task) => {
subItem.forEach((sub) => {
preconditionCheck(sub) &&
setTaskData(addObjectToArray(taskData, task, sub));
});
};
useEffect(() => {
console.log(taskData); //Printing the data here
}, [taskData]);
const makeUniqueProducts = (dataValues) => {
dataValues.forEach((dataItem) => {
subItemMaker(dataItem.subItemValues, dataItem.name);
});
};
useEffect(() => {
makeUniqueProducts(data); //Data changing function
}, [data]);
return (
<>
{JSON.stringify(taskData)} {/*Here it is not updating */}
</>
);
};
export default DataManipulation;
我正在更改数据并更新任务数据状态。 它正在更新,我可以在 useEffect 中看到,但在渲染中看不到。 请在这里帮助我。
我猜你的函数在一个循环内多次更新
taskData
,因此React可能出于性能原因批量更新这些更新。我会做这样的事情:
import React, { useState, useEffect, useCallback } from 'react';
const DataManipulation = ({ data }) => {
const [taskData, setTaskData] = useState([]);
const addObjectToArray = useCallback((array, task, sub) => {
return [...array, { task, sub }];
}, []);
const subItemMaker = useCallback((subItem, task) => {
// create a new array of items, then updates the state once with all new items.
const newItems = subItem.reduce((acc, sub) => {
if (preconditionCheck(sub)) {
return addObjectToArray(acc, task, sub);
}
return acc;
}, []);
setTaskData(prevTaskData => [...prevTaskData, ...newItems]);
}, [addObjectToArray]);
const makeUniqueProducts = useCallback((dataValues) => {
dataValues.forEach((dataItem) => {
subItemMaker(dataItem.subItemValues, dataItem.name);
});
}, [subItemMaker]);
useEffect(() => {
makeUniqueProducts(data);
}, [data, makeUniqueProducts]);
useEffect(() => {
console.log(taskData);
}, [taskData]);
return (
<>
{JSON.stringify(taskData)}
</>
);
};
export default DataManipulation;
我使用了
setTaskData
的函数形式来确保我们始终使用最新的状态。