我有一个非常基本的Person
类,它需要一个名为data
的参数。
class Person implements PersonInterface {
constructor(public data) {
}
get name(): string {
return this.data.name;
}
}
const person: PersonInterface = new Person({ name: "Aristona });
在我的Redux存储中,我将所有人保存在一个数组中,如下所示:
[Person, Person, Person, Person]
用户可以编辑一个Person
的name属性。所以我的reducer看起来像这样:
case Constants.PERSON_UPDATE_SUCCESS:
const person = Object.assign({}, action.payload.person.data, {
name: action.payload.name
});
return {
...state,
persons: [
person,
...state.persons.filter(p => p.id !== person.id)
]
};
因为Object.assign
返回data
属性,所以它不起作用。我需要的是data
属性已更新的Person
对象。如果我可以改变数据,它将如下所示:
person.name = action.payload.name;
否则,我的persons数组将如下所示:
[Person, Person, Person, Person, Object] // Object is data
它会打断所有的迭代。
我试着这么做:
const updatedData = Object.assign({}, action.payload.person.data, {
name: action.payload.name
});
const person: PersonInterface = new Person(updatedData);
虽然理论上它是可行的,但遗憾的是,如果不对PersonFactory
类进行重大更改,我就无法示例化这样的类。
有没有办法在不破坏Redux的不变性的情况下实现这一点?
谢谢你。
2条答案
按热度按时间km0tfn4u1#
虽然我同意Faris的观点,即在Redux中存储类示例不是一个好的实践,但是
其中
...
是更新的数据。7y4bm7vi2#
The first principle of redux's three principles says
The state of your whole application is stored in an object tree within a single store. This makes it easy to create universal apps, as the state from your server can be serialized and hydrated into the client with no extra coding effort...
so consider changing your state to have only serializable data.
persons
branch of the state.new
Person on every update.[2]: http://1)%20It%20is%20not%20a%20good%20practice%20to%20store%20class%20instances%20in%20your%20state%20%20The%20first%20principle%20of%20redux's%20three%20principles%20says%20%20%20%3E%20The%20state%20of%20your%20whole%20application%20is%20stored%20in%20an%20object%20tree%20within%20a%20single%20store.%20This%20makes%20it%20easy%20to%20create%20universal%20apps,%20as%20the%20state%20from%20your%20server%20can%20be%20serialized%20and%20hydrated%20into%20the%20client%20with%20no%20extra%20coding%20effort...%20%20so%20consider%20changing%20your%20state%20to%20have%20only%20serializable%20data.%20%202)%20It%20is%20a%20good%20practice%20to%20use%20tools%20like%20 immutablejs ,%20it%20will%20take%20all%20immutability%20issues%20away%20and%20forever.%20%203)%20It%20is%20a%20good%20practice%20to%20use%20split%20your%20reducer%20functions,%20consier%20using%20%20%20%20%20 %5C[1%5C]:%20https://fa cebook.github.io/immutable-js/%20%20%20%20%20 1 :%20http://redux.js.org/docs/api/combineReducers.html