【发布时间】:2019-10-23 22:03:33
【问题描述】:
我正在尝试在 ReactJS 中切换组件的状态,但我收到一条错误消息:
已超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。
我的代码中没有看到无限循环,有人可以帮忙吗?
ReactJS 组件代码:
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;
【问题讨论】:
-
将
this.toggle()更改为this.toggle或{()=> this.toggle()} -
另一个改进,虽然与您的问题无关:将
toggle(){...}转换为toggle = () => {...},这样您就不需要bind它了! -
谢谢@learner。你也帮了我。您能否解释一下您的解决方案背后的原因。这两者有什么区别?
-
@Shamim 这是调用现有函数和将引用传递给函数之间的区别。了解我们正在编写在用户执行某项操作时显示和触发的代码,而不是在用户加载页面时立即触发的代码,这很有帮助。 reactjs.org/docs/faq-functions.html
标签: javascript reactjs react-native