gpt4 book ai didi

reactjs - react 异步组件WillUnmount

转载 作者:行者123 更新时间:2023-12-04 13:45:14 25 4
gpt4 key购买 nike

从 React 16 开始,componentWillMount 的顺序和 componentWillUnmount由于支持异步 componentWillUnmount,不再保证。

然而,在我们使用React + Redux的项目中,从页面A导航到页面B,例如页面A调用componentWillUnmount清理应用程序状态然后跳转到页面B,它调用componentWillMount获取数据并更新状态。由于无法控制它们的顺序,有时状态会困惑。

这个问题的最佳解决方案是什么?

最佳答案

有几种方法可以解决此类问题。但几乎所有这些都是不好的做法(例如,在第一次渲染中使用带有 return null 的 HOC,然后清除并执行异步查询等)我不推荐这种方式。
所以我建议多花一点时间重构你的架构,并在 Redux 中分离状态。
我找到了一篇关于这个问题的 Dan Abramov 的好帖子:https://github.com/facebook/react/issues/11106#issuecomment-344573660

The easiest way to do so is to not reuse the same part of the tree in such a way. Think about it: components are generally expected to be independent. What happens if you render two such "exclusive" components at the same time? They will conflict. This doesn't seem like the right component thinking.

I understand it is more code to avoid such patterns, but in my experence replacing a single state tree branch with an object or an array was enough. For example you can key it by ID (even a dynamically generated one), and then instead of tearing down the old one in time for the new component mounting, you can just point the new component to the branch with new ID, while keeping the old one alive. Then eventually you can emit an action that cleans up unused state branches and only leaves the one with the most recent ID.

关于reactjs - react 异步组件WillUnmount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50050723/

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