更新地图内的状态挂钩

时间:2020-10-08 18:50:41

标签: reactjs react-hooks

我想更新地图内的状态挂钩。这是示例:

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>
  );
};

我想计算总收入并将其传播到其他地方。如果我在地图内使用状态挂钩,则会收到以下错误:

Too many re-renders. React limits the number of renders to prevent an infinite loop.

我如何做到这一点?

1 个答案:

答案 0 :(得分:2)

我将在返回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>