有没有办法将动态 JSON 保存到 Mobx 状态树中?

Is there a way to save dynamic JSON into Mobx State Tree?

我之前使用的是 Redux,将动态 JSON 保存到商店中非常容易。我在想,我们如何在不实际定义模型结构的情况下在 Mobx-State-Tree 中做同样的事情。

.model({
    data:types.array(...)
)}

我正在尝试,但我又需要在其中定义 JSON 数组结构。

使用 mobx 状态树的整个想法是在您的应用程序中定义隐式数据类型。

但是如果出于某种原因你想保存JSON而不定义就是使用JSON.stringify({...})

将其转换成字符串

模型实际上是一个字符串

.model({
    data:types.string
)}

然后就可以用动作把JSON存进去

.actions((self) => ({
   saveJSON(jsonData){
        self.data = JSON.stringify(jsonData)        
      }
})

然后您可以在任何地方使用此 JSON,方法是使用视图

调用 store.getJson 属性 和 JSON.parse()
   views((self) => ({
      get getJson(){
         return JSON.parse(self.data)
      }
    })

我需要这样做,因为我收到了定义明确的类型的对象,但该类型包含一个 config 字段,可以是任何 json.

我通过定义在 MST 中做到了:

export const AnyJsonValue = types.union(
    types.string,
    types.number,
    types.integer,
    types.Date,
    types.boolean,
    types.map(types.late(() => JsonValue)),
    types.array(types.late(() => JsonValue)),
    types.undefined,
    types.null
);

然后像这样使用它:

export const MyObject = types.model("MyObject", {
        uuid: types.identifier,
        name: types.string,
        config: types.maybeNull(types.map(AnyJsonValue)),
        ...
});

如果您有一些限制,您仍然可以设置它们。 例如,如果您希望 config 为 null,或者嵌套任何 json 的字典(因此 config 不能是文字或数组,但可以是包含它们的字典), 你可以使用类型: t.maybeNull(t.map(JsonValue)).