我刚刚开始使用reasonML和graphql,并构建了一个简单的反应组件,用于从世界杯API中检索数据。我的代码如下:
[@bs.module] external gql: ReasonApolloTypes.gql = "graphql-tag";
module GetMatches = [%graphql
{|
query getMatches($id: ID!){
matches(id: $id) {
date
homeTeam {name}
awayTeam {name}
homeScore
awayScore
goals {
scorer {
name
}
time
}
}
}
|}
];
module GetMatchesQuery = ReasonApollo.CreateQuery(GetMatches);
let component = ReasonReact.statelessComponent("Matches");
let make = _children => {
...component,
render: _self => {
let matchParam = GetMatches.make(~id="300331511", ());
<GetMatchesQuery variables=matchParam##variables>
...{
({result}) =>
switch (result) {
| Loading => <div> {ReasonReact.string("Loading")} </div>
| Error(error) =>
<div> {ReasonReact.string(error##message)} </div>
| Data(response) => <Matches matches=response##matches />
}
}
</GetMatchesQuery>;
},
};
匹配组件
let component = ReasonReact.statelessComponent("Matches");
let make = (~matches, _children) => {
...component,
render: _self =>
<div>
{
matches
|> Js.Array.map(match => <Match match key=match##id />)
|> ReasonReact.array
}
</div>,
};
但是我收到了这个错误:
This has type:
option(Js.Array.t(option({. "awayScore": option(int),
"awayTeam": option({. "name": option(string)}),
"date": option(string),
"goals": option(Js.Array.t(option({. "scorer":
option(
{. "name":
option(
string)}),
"time":
option(
string)}))),
"homeScore": option(int),
"homeTeam": option({. "name": option(string)})})))
But somewhere wanted:
Js.Array.t(Js.t(({.. id: string} as 'a))) (defined as array(Js.t('a)))
我很确定这里缺少一些上下文,并且你的文件顶部有open Belt
之类的东西。
类型错误说response##matches
是array
中的option
,但是数组元素本身也在option
s中,这是非常奇怪的。所以我的理论是graphql-ppx
生成的代码使用类似数组索引的东西,这转换为对Array.get
的调用,如果超出范围,标准库中抛出异常,但在Belt
和许多其他标准库替换中,返回option
。
这是使用ppx
s的许多问题之一。它不是孤立地生成代码,并且可以与代码的其余部分进行奇怪的交互,并且调试起来并不容易。