Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
316 views
Welcome To Ask or Share your Answers For Others

1 Answer

I'd calculate the value in standalone statements before returning the JSX:

const App = () => {
  const [sampleMap, setSampleMap] = React.useState([
    { id: 1, name: "John", income: 100 },
    { id: 2, name: "George", income: 200 }
  ]);

  const netIncome = sampleMap.reduce((a, b) => a + b.income, 0);
  return (
    <div className="App">
      <div>I want to update this after iterating over the map:<b>{netIncome}</b></div>
      {sampleMap.map((value, key) => (
          <div key={key}>
            {value.name}
            {" - "}
            {value.income}
          </div> 
      ))}
      <div>net income:{netIncome}</div>
    </div>
  );
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...