【问题标题】:How to Initialise leaf/child stores of MobX State Tree如何初始化 MobX 状态树的叶/子存储
【发布时间】:2020-01-16 07:21:27
【问题描述】:

我的 MobX 状态树模型是这样的

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 是根存储。

我想创建AppStore 并为ProductStore 初始化以下数据。我创建了以下函数来初始化和创建商店:

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

任何帮助将不胜感激。

【问题讨论】:

    标签: reactjs next.js mobx-state-tree


    【解决方案1】:

    初始数据可以这样给出

    AppStore.create({
      productStore: {
        items: [
          {
              name: 'Product 1',
              price: 150
          },
          {
              name: 'Product 2',
              price: 170
          }
        ]
      }
    });
    

    因为ProductStore 在您的AppStore 中的productStore 键下使用。

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多