0

我使用 reason-apollo 从服务器获取数据。它返回我的数据类型(vscode 向我显示这种类型):

option(
  Js.t(
    < count : int;
  rows : [ `User of
             < firstName : string; id : string; lastName : string;
               userName : string >
             Js.t
         | `Node of < id : string > Js.t ] option Js.Array.t >
  )
)

我不太了解“行”的类型,也无法从中获取数据。我试过这个:

switch response##users {
   | None => ReasonReact.string("none")
   | Some(data) => {
      data##rows |> Array.map(optionalRow => {
         switch optionalRow {
            | None => ReasonReact.string("none")
            | Some(row) => ReasonReact.string(row##firstName);   
         }
      });
      ReasonReact.string("test");
   }
};

但错误如下:

This has type:
  array(option(Js.t(({.. firstName: string} as 'a)))) =>
  array(ReasonReact.reactElement)
But somewhere wanted:
  Js.Array.t(option([ `Node({. "id": string})
                    | `User({. "firstName": string, "id": string,
                              "lastName": string, "userName": string}) ])) =>
  'b

The incompatible parts:
  array(option(Js.t('a)))
  vs
  Js.Array.t(option([ `Node({. "id": string})
                    | `User({. "firstName": string, "id": string,
                              "lastName": string, "userName": string}) ]))
    (defined as
    array(option([ `Node({. "id": string})
                 | `User({. "firstName": string, "id": string,
                           "lastName": string, "userName": string}) ])))

  Further expanded:
    Js.t('a)
    vs
    [ `Node({. "id": string})
    | `User({. "firstName": string, "id": string, "lastName": string,
              "userName": string}) ]

如何从结果中获取“名字”?

4

1 回答 1

0

啊,很清楚,这是一个多态变体,这里是如何获取名字的片段。

...
switch optionalRow {
   | None => ReasonReact.string("none")
   | Some(row) => {
      switch row {
         | `User(u) => ReasonReact.string(u##firstName)
         | `Node(n) => ReasonReact.string("test")
      };
      ReasonReact.string("test");
   }
}
...
于 2019-04-03T07:54:21.277 回答