【问题标题】:Update state hooks inside map更新地图内的状态挂钩
【发布时间】:2020-10-08 18:50:41
【问题描述】:

我想更新地图中的状态挂钩。示例如下:

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.

我怎样才能做到这一点?

【问题讨论】:

  • 每次渲染组件时,都会为 sampleMap 中的每个项目更新一次总状态,从而导致重新渲染,这意味着您为样本中的每个项目更新一次总状态,从而导致重新渲染,这意味着......为什么不只是做例如sampleMap.reduce((total, { income }) =&gt; total + income, 0)?
  • 我出于好奇问道。我想看看我是否可以运行一次循环。我不知道为什么我收到了反对票!

标签: reactjs react-hooks


【解决方案1】:

我会在独立语句中计算值返回 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>

【讨论】:

    猜你喜欢
    • 2021-03-22
    • 1970-01-01
    • 2020-01-23
    • 2021-06-06
    • 2020-05-31
    • 2019-09-23
    • 1970-01-01
    • 2022-12-06
    • 2021-10-23
    相关资源
    最近更新 更多