为什么redux商店应该可序列化?

为什么redux商店应该可序列化?

问题描述:

在阅读redux文档时,我发现文档提到了这个:

When reading the redux doc I found that the doc mentioned this:


尽管如此,你应该尽力保持状态可序列化。
不要在里面放任何你不能轻易变成JSON的东西。

Still, you should do your best to keep the state serializable. Don't put anything inside it that you can't easily turn into JSON.

所以我的问题是,什么是保持状态可序列化的好处?
或者,如果我将不可序列化的数据存入商店,我会遇到什么困难?

So my question is, what's the benefit of keeping state serializable? Or, what difficulties I may have if I put non-serializable data into store?

我相信这并不是redux独有的 - Flux,甚至是React当地州也提出同样的建议。

And I believe this is not unique to redux - Flux, even React local state suggest the same thing.

这里有一个例子让我说清楚。假设商店结构是这样的。

To make me clear here is an example. Suppose the store structure is like this.

{
    books: { 
        1: { id: 1, name: "Book 1", author_id: 4 }
    },
    authors: {
        4: { id: 4, name: "Author 4" }
    }
}

这应该看起来都不错。但是,当我尝试访问Book 1的作者时,我必须编写如下代码:

This should all looks good. However when I try to access "the author of Book 1", I have to write code like this:

let book = store.getState().books[book_id];
let author = store.getState().authors[book.author_id];

现在,我要定义一个类:

Now, I'm going to define a class:

class Book {
    getAuthor() {
        return store.getState().authors[this.author_id];
    }
}

我的商店将是:

{
    books: {
        1: Book(id=1, name="Book 1")
    },
    ...
}

这样我就可以得到作者通过使用:

So that I can get the author easily by using:

let author = store.getState().books[book_id].getAuthor();

第二种方法可以让书对象知道如何检索作者数据,所以来电者不需要知道书籍和作者之间的关系。那么,为什么我们不使用它,而不是像方法#1那样在商店中保留普通对象?

The 2nd approach could make the "book" object aware of how to retrieve the author data, so the caller does not need to know the relation between books and authors. Then, why we are not using it, instead of keeping "plain object" in the store just as approach #1?

任何想法都值得赞赏。

直接来自 redux常见问题解答

我可以在我的商店状态中添加函数,承诺或其他不可序列化的项吗?

它强烈建议您只将简单的可序列化对象,数组和基元放入商店。从技术上讲,可以将不可序列化的项目插入到商店中,但这样做会破坏商店内容的持久性和再水化能力,并且会影响时间旅行的调试。

It is highly recommended that you only put plain serializable objects, arrays, and primitives into your store. It's technically possible to insert non-serializable items into the store, but doing so can break the ability to persist and rehydrate the contents of a store, as well as interfere with time-travel debugging.

如果您对持久性和时间旅行调试可能无法正常工作等问题感到满意,那么我们非常欢迎您将非可序列化的项目放入Redux商店。最终,它是您的应用程序,您如何实现它取决于您。与Redux的许多其他事情一样,请确保您了解所涉及的权衡。

If you are okay with things like persistence and time-travel debugging potentially not working as intended, then you are totally welcome to put non-serializable items into your Redux store. Ultimately, it's your application, and how you implement it is up to you. As with many other things about Redux, just be sure you understand what tradeoffs are involved.






进一步阅读:

  • What is time travel debugging?