return 如何将外部方法作为选项?

How can return an external method as an option?

我正在尝试为我可以在 Reason.useEffect 中调用的 XMLHttpRequest 创建一个模块。下面的代码我已经在单个实例中尝试过并且似乎可以工作,但我希望能够提供 Reason.useEffect 调用库的“中止”的能力:现在我正在给它 None 所以如果出现问题,React 什么都不做。

type request;
type response;
[@bs.new] external makeXMLHttpRequest: unit => request = "XMLHttpRequest";
[@bs.send] external addEventListener: (request, string, unit => unit) => unit = "addEventListener";
[@bs.get] external response: request => response = "response";
[@bs.send] external open_: (request, string, string) => unit = "open";
[@bs.send] external setRequestHeader: (request, string) => unit ="setRequestHeader";
[@bs.send] external send: request => unit = "send";
[@bs.send] external abort: request => unit = "abort";

[@bs.scope "JSON"][@bs.val] external parseResponse: response => {. "message": array(string)} = "parse";

let send = (~responseCB, ~errorCB, ~apiURL) => {
    let request = makeXMLHttpRequest()

    request->addEventListener("load", ()  => responseCB( (request->response->parseResponse)##message ) )
    request->addEventListener("error", () => errorCB())
    request->open_("GET", apiURL)

    request->send
    /* How do I return the "request->abort" method as an option? */
    /* Some(request->abort) */
    None
}

我调用上面的代码:

let responseCB = (response) => setState(_previousState => LoadedDogs(response));
let errorCB = () => setState(_previousState => ErrorFetchingDogs);

React.useEffect0(
    () => XMLHttpRequest.send(
            ~responseCB,
            ~errorCB,
            ~apiURL="https://dog.ceo/api/breeds/image/random/3"
        )
);

非常 是 FP 的新手,已经有 30 多年的 C jocky 经验了。

如果我理解正确的话,因为你没有说如果你尝试做“显而易见的”你会得到什么错误,问题是 React.useEffect0 期望 option(unit => unit)Some(request->abort) 会立即执行 request->abort 和 return option(unit).

如果是这样,解决方案应该是创建一个 unit => unit 函数,在调用时简单地调用 request->abort

Some(() => request->abort)