簡體   English   中英

如何在 useEffect hook 中使用本地 scope?

[英]How to use local scope inside useEffect hook?

以下代碼工作正常:

useEffect(() => {
  const apiService = new APIClient('api address');
  var topicCommentsReq = new GetTopicDetailsRequest();
  topicCommentsReq.setTopicCid(Buffer.from("123", "hex"));
  apiService.getTopicDetails(topicCommentsReq, {}, function (err, response) {
    console.log(`response : ${JSON.stringify(response)}`);
  });
}

我想將此回調樣式 function 轉換為異步/等待樣式,所以我做了這樣的事情:

const promisifyFn =
  (fn: Function) =>
  (...args: any[]) =>
    new Promise((resolve, reject) => {
      return fn(...args, (err: Error, data: any) => {
        return err ? reject(err) : resolve(data);
      });
    });

useEffect(() => {
  (async () => {
    const apiService = new APIClient("api address");
    const topicCommentsReq = new GetTopicDetailsRequest();
    topicCommentsReq.setTopicCid(Buffer.from("123", "hex"));
    const getTopicDetails = promisifyFn(apiService.getTopicDetails);
    try {
      const res = await getTopicDetails(topicCommentsReq, {});
      console.log(`response : ${JSON.stringify(res)}`);
    } catch (e) {
      console.log(e);
    }
  })();
});

顯示以下錯誤消息:

TypeError: Cannot read properties of undefined (reading 'client_')
 if (callback !== undefined) {
      return this.client_.rpcCall(
        this.hostname_ +
          '/StelaPlatform.GRPC.API/GetTopicDetails',
        request,
        metadata || {},
        this.methodDescriptorGetTopicDetails,
        callback);
    }

我的猜測是這個問題與 lcoal scope 有關。當 function 在異步 function 中運行時,這個 scope 是不同的。 但是我一般應該如何解決這個問題呢?

問題是在將 function 引用傳遞給apiService.getTopicDetails時,它失去了它的this上下文。

為了在其原型中保留原型 function,您應該使用箭頭 function...

const getTopicDetails = promisifyFn((...args) =>
  apiService.getTopicDetails(...args));

Function.prototype.bind()

const getTopicDetails = promisifyFn(apiService.getTopicDetails.bind(apiService));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM