gpt4 book ai didi

javascript - React Refs 值得 setState 给出超过最大更新深度。

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:41 26 4
gpt4 key购买 nike

Helo 伙计们,我尝试使用 Refs 并在他的内部提供 this.setState 但它给出:

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.

我最近怎么样:

ref = {
(anchor) => this.setState({
anchor
})
} >

但是当我使用:

ref = {
(anchor) => this.state.anchor = anchor
} >

它有效..

在其他组件中,我也使用 this.setState 并且它运行良好,为什么?

最佳答案

ref是 React 中的一个特殊 Prop 。 React 将在组件挂载 时使用 DOM 元素调用 ref 回调,并在组件卸载 时使用 null 调用它>。 ref 更新发生在 componentDidMountcomponentDidUpdate 生命周期钩子(Hook)之前。所以在第一个例子中,当 ref props 回调函数被执行时,在挂载之前你使用 setState 改变了 state,所以组件再次启动mounting 由于状态变化。现在您处于无限通话循环中。

但是在第二种情况下,你直接改变了 state,这在 React 中是不应该做的,当你通过直接改变 state 来更新状态时,它永远不会踢重新渲染。所以没有发生Infinite call。它正常安装。

注意:ref 不是改变状态的地方。 Refs 提供了一种访问 DOM 节点或在 render 方法中创建的 React 元素的方法。 根据文档。

希望对您有所帮助。

关于javascript - React Refs 值得 setState 给出超过最大更新深度。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52120906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com