为什么addChangeListener应该在componentDidMount而不是componentWillMount? [英] Why should addChangeListener be in componentDidMount instead of componentWillMount?

查看:111
本文介绍了为什么addChangeListener应该在componentDidMount而不是componentWillMount?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到这一行作为另一个问题的答案:



componentWillMount应该是componentDidMount,否则你将在节点中泄漏事件发射器。 / p>

我真的不明白。有人可以更详细地解释一下吗?



更多信息:



使用flux构建反应应用程序,作为在初始渲染中,子组件计算一些数据。理想情况下,在计算此数据之后,我想调用一个动作,用一部分新数据更新商店的状态。



通常,更新商店的状态会发出导致重新呈现的更改事件。但是,因为更改侦听器直到componentDidMount(而不是componentWillMount)才被添加,所以我的顶级组件无法侦听初始渲染期间发生的更改并启动重新渲染。



如果我将addChangeListener移动到似乎可以修复此问题的componentWillMount,但上面的引用表明这是一个坏主意?

解决方案

如果没有更多的背景,很难理解这句话的含义。我可以告诉你的是,这两种方法之间存在巨大差异。



一方面, componentWillMount 在将组件实际添加到DOM之前调用。这是您必须更新组件状态并在浏览器呈现组件之前呈现它的最后一次机会。



另一方面,组件附加到DOM(真正的组件)后,将调用componentDidMount



您需要的实际取决于您的用例。通常, componentDidMount 用于与其他库(如jQuery)集成,它提供了一种修改组件呈现的HTML的方法。



我建议你阅读这些链接:




I saw this line as an answer to another question on here:

"componentWillMount should be componentDidMount, or else you'll leak event emitters in node."

and I don't really understand it. Can someone explain with more detail?

More info:

Building a react application with flux, as part of the initial render, a child component computes some data. Ideally, after this data is computed, I would like to call an action that updates the store's state with a portion of this new data.

Normally, updating the store's state emits a change event that causes a re-render. However, because the change listener isn't being added until componentDidMount (rather than in componentWillMount), my top level component isn't able to listen for the change that occurs during the initial render and initiate a re-render.

If I move the addChangeListener to componentWillMount that would seem to fix this issue, but the above quote suggests that this is a bad idea?

解决方案

Is hard to understand what that quote means without more context. What I can tell you is that there are huge differences between the two of those methods.

On one hand, componentWillMount is called before the component is actually added to the DOM. This is the last chance you have to update component's state and get it rendered before the component is rendered by the browser.

On the other hand, componentDidMount is called once the component has been attached to the DOM (the real one).

What you need really depends on your use case. In general, componentDidMount is used to integrate with other libraries (like jQuery), it provides a way to modify the HTML rendered by the component.

I suggest you to read these links:

这篇关于为什么addChangeListener应该在componentDidMount而不是componentWillMount?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆