gpt4 book ai didi

javascript - 为什么我的 Redux store 应该是可序列化的?

转载 作者:可可西里 更新时间:2023-11-01 01:40:45 24 4
gpt4 key购买 nike

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

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.

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

而且我相信这不是 redux 独有的 - Flux,甚至 React 本地状态也暗示了同样的事情。


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

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

这看起来应该不错。但是,当我尝试访问“第一本书的作者”时,我必须编写如下代码:

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

现在,我要定义一个类:

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

我的商店将是:

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

这样我就可以很容易地得到作者:

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

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

欢迎任何想法。

最佳答案

直接来自 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.


进一步阅读:

关于javascript - 为什么我的 Redux store 应该是可序列化的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941079/

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