[英]Error: Max update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate
I want to do in class component what I did in function component, but it gives an error.我想在 class 组件中执行我在 function 组件中执行的操作,但出现错误。 How can I fix?
我该如何解决?
function component: function 组件:
const [listBtnClassName, setListBtnClassName] = useState("listBtnPulse"); useEffect(() => { if (showGrid) { setListBtnClassName("listBtnPulseNone"); } }, [showGrid]); <PageFilter listBtnClassName={listBtnClassName} ></PageFilter>
class component: class 组件:
this.state = { listBtnClassName: "listBtnPulse", }; componentDidUpdate() { if (this.props.showGrid) { this.setState({ listBtnClassName: "listBtnPulseNone" }); } } <PageFilter listBtnClassName={this.state.listBtnClassName} ></PageFilter>
Error: Maximum update depth exceeded.错误:超出最大更新深度。 This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,就会发生这种情况。 React limits the number of nested updates to prevent infinite loops.
React 限制嵌套更新的数量以防止无限循环。
You need to make sure the showGrid
from the previous props is not true
, but the showGrid
from current props is true
.您需要确保来自先前道具的
showGrid
不是true
,但来自当前道具的showGrid
是true
。
See this document for more information.有关详细信息,请参阅此文档。
this.state = { listBtnClassName: "listBtnPulse", }; componentDidUpdate(prevProps) { if (.prevProps.showGrid && this.props.showGrid) { this:setState({ listBtnClassName; "listBtnPulseNone" }); } }
<PageFilter listBtnClassName={this.state.listBtnClassName} ></PageFilter>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.