简体   繁体   English

错误:超过最大更新深度。 在反应

[英]Error: Maximum update depth exceeded. in react

Iam new to React this is my first Simple small project.我是 React 新手,这是我的第一个简单的小项目。 Iam getting this error and I found the reason why it is happening.我收到了这个错误,我找到了它发生的原因。 But I don't know where my code repeatedly rendering that particular component.但我不知道我的代码在哪里重复渲染该特定组件。 please help me to tackle this issue.请帮我解决这个问题。

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'));```

This is my error state这是我的错误 state

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

This is the offending line这是违规行

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

This is because the function is being called on render, instead of when it is clicked, to get it to only run on click you need to wrap it in an anonymous function, like so...这是因为 function 是在渲染时调用的,而不是在单击时调用,要使其仅在单击时运行,您需要将其包装在匿名 function 中,就像这样......

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM