Redux 存储会导致内存泄漏吗?

Can a Redux store lead to a memory leak?

我有一个仪表板应用程序,其中有几个图表按设定的时间间隔更新。我的第一个想法是更新商店中的数据,然后让所有图表从那里获取数据。

但这会导致内存泄漏吗?由于每次数据更改时 Redux 都会创建一个新存储并保留旧存储。每秒约 2mb 的数据会堆积并导致应用程序崩溃吗?

我看到的替代方案是将数据保持在本地状态(使用 setState)。 我希望一些更有经验的 React/Redux 开发者可以就此向我提出建议。谢谢!

不建议在用户浏览器上堆积2MB数据/秒。 Redux store 是浏览器上的客户端。据我所知,关于内存泄漏的问题的另一部分并没有发生。一些有用的链接是:

Diagnose memory leaks using Chrome devtools

Four types of memory leaks to watch out for

"Since Redux creates a new store every time the data charges and keeps the old ones."

Vanilla Redux 不会那样做,否则 every Redux 存储会泄漏。事实上,您的应用程序的其余部分持有对状态的引用将阻止它被清理。

例如

window.states = []
store.subscribe(() => {
  window.states.push(store.getState())
})

会导致内存无限增长。

此外,一些 Redux 开发工具确实会泄漏以提供时间旅行功能,因此请确保在您的生产构建中关闭它们。

首先,确实听起来数据量很大。您的客户端应用程序实际上需要那么多的数据吗?

其次,Redux 没有"create new stores"。假设您遵循推荐的数据更新方法,旧数据引用将被丢弃并将被垃圾收集。默认情况下,Redux 本身不会保留对旧状态树的引用,尽管 Redux DevTools 这样做是为了启用时间旅行调试。

您可能需要通读 Redux 文档中的几个部分。具体请参见 http://redux.js.org/docs/faq/Performance.html , http://redux.js.org/docs/recipes/StructuringReducers.html .

您可能还想浏览我的 Redux addons catalog,其中包括可以执行批处理更新等操作的插件。

Dan Abramov,Redux 的创建者解决了这个问题here,就像这样:

Note that sometimes people get confused about Redux and assume that on every action, the state tree has to be cloned deeply. This is absolutely not the case. Only the parts that changed need to change their references. For example, if an action causes a change to one item in an array, indeed, that item and the array will need to be copied, however, all other elements in the array will keep their identities. Because most of the times actions are very targeted and affect a few state keys, and because Redux encourages normalizing data so that the data structures are not deeply nested, this is much less of a problem for typical webapps than one might imagine.

我认为这是答案的核心。