gpt4 book ai didi

reactjs - Immer 是否允许我们在 redux reducer 中存储类实例?

转载 作者:行者123 更新时间:2023-12-05 03:52:50 26 4
gpt4 key购买 nike

Redux Style-Guide状态:

Avoid putting non-serializable values such as Promises, Symbols, Maps/Sets, functions, or class instances into the Redux store state or dispatched actions. This ensures that capabilities such as debugging via the Redux DevTools will work as expected. It also ensures that the UI will update as expected.

Immer - Complex-Objects

Every other object must use the immerable symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.


class Foo {
[immerable] = true // Option 1

constructor() {
this[immerable] = true // Option 2
}
}

Foo[immerable] = true // Option 3

我知道我可以有一个类实例化简器...但是我应该吗?

我假设这样做的危险是时间旅行和 Redux DevTools 可能会被破坏 - 但 immer 将防止 reducer 之外的任何突变。

Example :

import { immerable } from "immer";

class MyClass {
constructor() {
this[immerable] = true;
this.data = [];
}

addData(row = "") {
this.data.push(row);
}

prettyPrint() {
this.data.map((txt, index) => console.log(`Row ${index}: ${txt}`));
}
}
const example = createSlice({
name: "example",
initialState: new MyClass(),
reducers: {
addItem: (state, action) => {
state.addData(action.payload);
}
}
});

let state = example.reducer(undefined, example.actions.addItem("Test"));
console.log(state.prettyPrint());

state = example.reducer(state, example.actions.addItem("Test Me too"));
console.log(state.prettyPrint());

console.log(state);

//Will error
// state.addData('Will Error');

这样做的原因是什么?我们在大类中有复杂的业务逻辑。与示例 prettyPrint 一样,我们有一些复杂的功能封装在我们在 React 应用程序中使用的类实例中。

我对该方法的另一个想法是在 reducer 内部进行实例化和序列化,以便我们的类实例的 json 表示仅存储在 reducer 内部。如果我可以避免必须执行实例化-> 序列化每个操作,并且可以访问状态树上的实用程序函数,那么这将是首选。

最佳答案

你根本不应该为此使用类。

只需将您的数据 直接存储为JS 对象或数组,然后使用selectors做 pretty-print 。

关于reactjs - Immer 是否允许我们在 redux reducer 中存储类实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62025410/

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