2

I'm fetching data from external API, and want to store it in MST store as array. But the result is always proxy, not the object I wanted.

This is result from API:

(4) [Object, Object, Object, Object]
0:Object
id:1
name: "Foobar"
created_at: "2019-04-27 09:09:29"
updated_at:null
deleted_at:null
__proto__:Object
.........

This is my store:


const TypesModel = types.model({
  name: types.maybe(types.string),
  created_at: types.maybe(types.string)
});

export const TransactionTypeStore = types
  .model("TransactionTypeStore", {
    transaction_types: types.optional(types.array(TypesModel), [])
  })
  .actions(self => ({
    getTypes: flow(function*(token) {
      try {
        const res = yield typesApi
          .headers({ Authorization: `Bearer ${token}` })
          .get()
          .json();

        console.log("result", res);

        self.transaction_types = res;

        // res.map(data => {
        //   self.transaction_types.push(data);
        // });
      } catch (err) {
        console.log(err);
      }
    })
  }));

And this is console.log of my MST store:

transaction_types:Proxy
[[Handler]]:Object
[[Target]]:Array(4)
0:ObjectNode
1:ObjectNode
2:ObjectNode
3:ObjectNode
$treenode:ObjectNode
length:4
toJSON:function toJSON()
Symbol(mobx administration):ObservableArrayAdministration
__proto__:Array(0)
[[IsRevoked]]:false
.........

Does anyone know how to deal with this kind of problem?

4

1 回答 1

0

你的res对象是什么样子的,它应该是一个{ name, created_at }对象数组——不多不少,不是吗?也transaction_types永远不会只是一个数组 -types.array是一个复杂的 MST 类型,它有一些数组方法,但它不是一个数组。这是一个可观察的数组,你应该相应地对待它。

另请查看 Michel Weststrate 本人制作的视频教程:使用可观察对象、数组和地图在 MobX 中存储状态,以更好地掌握这个概念(创建一个帐户,它是免费的)。

于 2019-06-12T06:57:17.880 回答