Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

javascript - Why should my Redux store be serializable?

When reading the redux docs I found this:

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?

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" }
    }
}

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];
    }
}

And my store will be:

{
    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();

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?

Any ideas are appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Directly from the redux FAQs:

Can I put functions, promises, or other non-serializable items in my store state?

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.

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.


Further reading:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...