【问题标题】:Error: Maximum update depth exceeded. in react错误:超过最大更新深度。在反应
【发布时间】:2022-01-05 09:08:40
【问题描述】:

我是 React 新手,这是我的第一个简单的小项目。我收到了这个错误,我找到了它发生的原因。但我不知道我的代码在哪里重复渲染该特定组件。请帮我解决这个问题。

function Button(props)
{  
  return(<button onClick={props.count(props.value)}>{props.value}</button>);
}
function Display(props)
{
  return(<div>{props.messege}</div>);
}
function App()
{
  const[counter,setCounter]=useState(0);
  const countfunction=(val)=> setCounter(counter+val);
  return(
  <div>
      <Button count={countfunction} value={10} />
      <Button count={countfunction} value={5} />
      <Button count={countfunction} value={1} />
      <Button count={countfunction} value={120} />
      <Display messege={counter}/>
  </div>
  );
}

ReactDOM.render(<App/>,document.getElementById('mountNode'));```

这是我的错误状态

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
    at checkForNestedUpdates 
    at scheduleUpdateOnFiber 
    at dispatchAction 
    at Object.countfunction [as count] 
    at Button 
    at renderWithHooks 
    at updateFunctionComponent 
    at beginWork 
    at beginWork$1 
    at performUnitOfWork

【问题讨论】:

  • 这个问题是由于onClick按钮的即时调用导致的,只需在此处添加一个箭头功能

标签: javascript reactjs react-hooks


【解决方案1】:

这是违规行

return(<button onClick={props.count(props.value)}>{props.value}</button>);

这是因为函数是在渲染时调用的,而不是在点击时调用,要让它只在点击时运行,你需要将它包装在一个匿名函数中,就像这样......

return(<button onClick={() => props.count(props.value)}>{props.value}</button>);

【讨论】:

    猜你喜欢
    • 2021-05-15
    • 2021-06-20
    • 2021-10-13
    • 2021-09-06
    • 1970-01-01
    • 2021-07-12
    • 2019-02-14
    • 2019-07-17
    • 1970-01-01
    相关资源
    最近更新 更多