I want to update a state hook inside a map. Here is the example:
const App = () => {
const [total, setTotal] = useState(); // I want to use it but I receive an error
const [sampleMap, setSampleMap] = useState([
{ id: 1, name: "John", income: 100 },
{ id: 2, name: "George", income: 200 }
]);
let netIncome = 0;
return (
<div className="App">
<div>I want to update this after iterating over the map:<b>{netIncome}</b></div>
{sampleMap.map((value, key) => {
netIncome += value.income;
//setTotal(netIncome);
return (
<div key={key}>
{value.name}
{" - "}
{value.income}
</div>
);
})}
<div>net income:{netIncome}</div>
</div>
);
};
I want to calculate the total income and propagate it elsewhere. If I use a state hook inside the map, I receive the following error:
Too many re-renders. React limits the number of renders to prevent an infinite loop.
How can I make this happen?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…