本文介绍了ReactJS:超出最大更新深度错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在 ReactJS 中切换组件的状态,但我收到一条错误消息:
I am trying to toggle the state of a component in ReactJS but I get an error stating:
已超出最大更新深度.当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,就会发生这种情况.React 限制嵌套更新的数量以防止无限循环.
我的代码中没有看到无限循环,有人可以帮忙吗?
I don't see the infinite loop in my code, can anyone help?
ReactJS 组件代码:
ReactJS component code:
import React, { Component } from 'react';
import styled from 'styled-components';
class Item extends React.Component {
constructor(props) {
super(props);
this.toggle= this.toggle.bind(this);
this.state = {
details: false
}
}
toggle(){
const currentState = this.state.details;
this.setState({ details: !currentState });
}
render() {
return (
<tr className="Item">
<td>{this.props.config.server}</td>
<td>{this.props.config.verbose}</td>
<td>{this.props.config.type}</td>
<td className={this.state.details ? "visible" : "hidden"}>PLACEHOLDER MORE INFO</td>
{<td><span onClick={this.toggle()}>Details</span></td>}
</tr>
)}
}
export default Item;
推荐答案
因为你在render方法中调用toggle会导致re-render和toggle会再次调用和re-rendering以此类推
that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on
代码中的这一行
{<td><span onClick={this.toggle()}>Details</span></td>}
你需要让 onClick
引用 this.toggle
而不是调用它
you need to make onClick
refer to this.toggle
not calling it
要修复问题,请执行此操作
{<td><span onClick={this.toggle}>Details</span></td>}
这篇关于ReactJS:超出最大更新深度错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!