如何有意减慢 React 状态更新 - 批量更新
有时我可能想卸载并重新安装其中包含新数据的组件。这可能看起来像:
setAllPosts(undefined);
setAllPosts(newArrayOfPosts);
因为 React 会批量更改状态,所以状态不会更改,具体取决于 newArrayOfPosts 的来源。我已经能够用 1 秒的 setTimeout() 破解解决方案,然后填写 setAllPosts(),但这感觉很错误。
有没有最佳实践方法来告诉 React 放慢速度一会儿?或者也许不批量更新这个特定的状态更改?
PS 我知道有更好的方法可以做到这一点,但我在第三方环境中工作,并且我所能访问的内容非常有限。
Occasionally I may want to unmount and remount a component with new data inside it. This could look like:
setAllPosts(undefined);
setAllPosts(newArrayOfPosts);
Because React batches state changes, depending on where the newArrayOfPosts is coming from, the state won't change. I've been able to hack a solution with a setTimeout() of 1 second and then filling in setAllPosts(), but this feels so wrong.
Is there a best practice way to tell React to slow down for a moment? or maybe to not batch update this particular state change?
P.S. I know there are better ways to do this, but I am working inside a third party environment and am pretty limited to what I have access to.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是你可以做到的 -
这用于取消批处理反应状态。这只是一种单一的方法。另一种方法是使用 setTimeout。请注意,在 React 18 版本中,setTimeouts 内的状态更新也会进行批处理 - 这称为自动批处理,但我们仍然可以通过使用不同的 setTimeouts 来实现这一点 -
只要确保保持时间差以排除批处理完成即可通过反应。
This is how you can do it -
This is used to un-batch the react states. This is just a single way of doing it. The other way could be to use
setTimeout
. Please note that with version 18 of react, state updates within setTimeouts are also being batched - this is known as Automatic Batching, but we still can achieve this by using different setTimeouts -Just make sure to keep a time difference to rule out the batching done by React.
一旦 React 18 可用(目前是候选版本),将会有一个函数可以强制更新不进行批处理:
flushSync
在那之前,您可能需要执行 setTimeout 方法(尽管它不会不需要是一整秒)。
是的,如果你能做点别的事情可能会更好。大多数时候,如果您想故意卸载/重新安装组件,最好通过使用
key
来实现,您可以在希望重新安装时更改该键。Once react 18 is available (it's currently a release-candidate) there will be a function that can force updates to not be batched:
flushSync
Until then, you may need to do the setTimeout approach (though it doesn't need to be a whole second).
Yeah, if you can do something else that would probably be better. Most of the time, if you want to deliberately unmount/remount a component, that is best achieved by using a
key
which you change when you want the remount to happen.听起来这个用例需要一个
useEffect()
,它具有基于您关心的事物的依赖关系,例如提供给该组件的另一条状态或道具。我什至看到过人们通过名为
count
或renderCount
的状态依赖项来触发useEffect()
的示例。不确定这是否一定是最佳实践,但这是解决问题的一种方法。It sounds like this use-case calls for a
useEffect()
with a dependency based on something you care about, like another piece of state or prop being provided to this component.I've even seen examples of people triggered
useEffect()
with a dependency of a piece of state calledcount
orrenderCount
. Not sure if this is necessarily best practice but it's one way to go about things.