Reactjs 如何初始化MobX状态树的叶/子存储
我的MobX状态树模型是这样的Reactjs 如何初始化MobX状态树的叶/子存储,reactjs,next.js,mobx-state-tree,Reactjs,Next.js,Mobx State Tree,我的MobX状态树模型是这样的 const ProductItem = types .model({ name: types.string, price: types.number }) .actions(self => ({ changePrice(newPrice) { self.price = newPrice; } })); const ProductStore
const ProductItem = types
.model({
name: types.string,
price: types.number
})
.actions(self => ({
changePrice(newPrice) {
self.price = newPrice;
}
}));
const ProductStore = types
.model({
items: types.optional(types.array(ProductItem), [])
})
.actions(self => ({
add(item) {
self.items.push(item);
}
}));
const AppStore = types.model('AppStore', {
productStore: types.maybeNull(ProductStore)
});
AppStore.create({
productStore: {
items: [
{
name: 'Product 1',
price: 150
},
{
name: 'Product 2',
price: 170
}
]
}
});
AppStore
是根存储
我想为ProductStore
创建AppStore
并初始化以下数据。我创建了以下函数来初始化和创建存储:
export const initializeStore = (isServer, snapshot = null) => {
if (isServer) {
AppStore.create({
.....
});
}
return store;
};
我不确定如何在AppStore.create()中使用此数组初始化ProductStore
:
items: [
{
name: 'Product 1',
price: 150
},
{
name: 'Product 2',
price: 170
}
]
任何帮助都将不胜感激。初始数据可以这样给出
const ProductItem = types
.model({
name: types.string,
price: types.number
})
.actions(self => ({
changePrice(newPrice) {
self.price = newPrice;
}
}));
const ProductStore = types
.model({
items: types.optional(types.array(ProductItem), [])
})
.actions(self => ({
add(item) {
self.items.push(item);
}
}));
const AppStore = types.model('AppStore', {
productStore: types.maybeNull(ProductStore)
});
AppStore.create({
productStore: {
items: [
{
name: 'Product 1',
price: 150
},
{
name: 'Product 2',
price: 170
}
]
}
});
由于ProductStore
在ProductStore
键下使用,在AppStore
中可以这样给出初始数据
const ProductItem = types
.model({
name: types.string,
price: types.number
})
.actions(self => ({
changePrice(newPrice) {
self.price = newPrice;
}
}));
const ProductStore = types
.model({
items: types.optional(types.array(ProductItem), [])
})
.actions(self => ({
add(item) {
self.items.push(item);
}
}));
const AppStore = types.model('AppStore', {
productStore: types.maybeNull(ProductStore)
});
AppStore.create({
productStore: {
items: [
{
name: 'Product 1',
price: 150
},
{
name: 'Product 2',
price: 170
}
]
}
});
由于ProductStore
在ProductStore
下使用,请在AppStore
中键入