[英]How to appropriately migrate from componentWillReceiveProps to getDerivedStateFromProps when 'this' is being used
I am trying to migrate my apps to do the React v16.3.* API, and it has been quite difficult to get rid of componentWillReceiveProps
. 我正在尝试迁移我的应用程序以使用React v16.3。* API,而摆脱componentWillReceiveProps
却非常困难。 I have components which are dependent on it and call the components other function in them. 我有依赖于它的组件,并在其中调用组件的其他功能。
Because getDerivedStateFromProps
is static, I can't easily do this anymore and I need help on how to appropriately. 因为getDerivedStateFromProps
是静态的,所以我再也不能轻易做到这一点,并且需要适当的帮助。 For this case in particular, I have a timeout function that resets whenever new props are received. 特别是在这种情况下,我有一个超时功能,每当收到新道具时,它就会重置。 It currently is as follows: 当前如下:
componentWillReceiveProps (nextProps) {
clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.dismiss(null, nextProps)
}, nextProps.timer)
}
As you can see I have this.timeout
and this.dismiss
which I cannot access anymore once the change is made to getDerivedStateFromProps
. 正如你可以看到我有this.timeout
和this.dismiss
这一次的变化来做出我不能再访问getDerivedStateFromProps
。 How to I deal with this? 我该如何处理? Is there a way to change this to be a getDerivedStateFromProps
static function or do I have to go about this a completely different way? 有没有办法将其更改为getDerivedStateFromProps
静态函数,或者我必须采用完全不同的方式进行此操作?
As @Kyle mentions, this doesn't belong in getDerivedStateFromProps
, but it might not be immediately obvious why you can safely do this in componentDidUpdate
. 正如@Kyle所提到的,这不属于getDerivedStateFromProps
,但是为什么您可以在componentDidUpdate
安全地执行此操作可能并不立即显而易见。
The reason you can is that you're only clearing and setting timers, which won't affect anything until after React has updated the DOM and finished executing. 您可以这样做的原因是,您只需要清除和设置计时器,直到React更新DOM并完成执行后,它才会受到影响。 Hence, it makes no difference if you do this in the pre-render componentWillReceiveProps
or the post-update componentDidUpdate
: 因此,如果在渲染前componentWillReceiveProps
或更新后componentDidUpdate
执行此操作,则没有任何区别:
componentDidUpdate()
clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.dismiss(null, this.props)
}, this.props.timer)
}
The React blog has some example migrations that may prove helpful. React博客提供了一些示例迁移 ,可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.