Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

reactjs - Update state hooks inside map

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...