简体   繁体   English

React Refs woth setState给出超出最大更新深度。

[英]React Refs woth setState giving Maximum update depth exceeded.

Helo guys, i trying to use Refs and to give this.setState inside his but it give: Helo伙计们,我试图使用Refs并将this.setState放在他的内部,但它给出了:

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限制嵌套更新的数量以防止无限循环。

How i'm doing: 我是怎么做的:

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

But when i use: 但是当我使用时:

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

it works.. 有用..

And in other component, i use this.setState also and it works perfectly, someone why? 在其他组件中,我也使用this.setState并且它工作得很好,有人为什么?

ref is a special props in React. ref是React中的特殊道具。 React will call the ref callback with the DOM element when the component mounts , and call it with null when it unmounts . 当组件安装时 ,React将使用DOM元素调用ref回调,并在卸载时使用null调用它。 ref updates happen before componentDidMount or componentDidUpdate lifecycle hooks. ref更新发生在componentDidMountcomponentDidUpdate生命周期挂钩之前。 So in the first example, when ref props callback function gets executed, before the mount you are changing the state using setState , so component again starts mounting due to state change. 因此,在第一个示例中,当执行ref props回调函数时,在使用setState更改state之前,因此组件会因状态更改而再次开始安装 And now your are in Infinite call loop. 现在你处于无限呼叫循环中。

But in the second case, you are directly mutating the state which never should be done in React, and when you update the state by mutating directly the state it never kicks re rendering. 但是在第二种情况下,你直接变异的state这不应该做的反应,当你通过突变直接更新状态state它永远不会踢重新渲染。 So there is no Infinite call is happening. 所以没有无限的召唤正在发生。 It mounted normally. 它正常安装。

Note: ref is not a place to change the state. 注意: ref不是改变状态的地方。 Refs provide a way to access DOM nodes or React elements created in the render method. Refs提供了一种访问DOM节点或在render方法中创建的React元素的方法。 As per the doc. 根据文件。

Hope that helps. 希望有所帮助。

1) refs must never be stored as a part of the component state. 1)refs绝不能作为组件状态的一部分存储。 Just assign it to the component's member like this: 只需将它分配给组件的成员,如下所示:

<div ref={ x => this.anchor = x } />

2) The component's state must never be modified directly. 2) 不得直接修改组件的状态。 No this.state.x = something , use setState so React could detect the change and make the UI update. 没有this.state.x = something ,请使用setState,以便React可以检测到更改并进行UI更新。

3) setState() must not be called directly from the render() (which causes infinite rendering loop). 3) 不能直接从render()调用setState() (这会导致无限的渲染循环)。

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

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