【问题标题】:Chrome Tab duplicate not making network requestChrome选项卡重复未发出网络请求
【发布时间】:2020-08-17 06:46:40
【问题描述】:

我在应用程序加载 (componentDidMount) 上有 3 个 api 调用。

当我重新加载页面或打开新选项卡时,会进行所有 api 调用,但在复制选项卡时只会触发其中一个。

如何在页面复制时触发所有 api 调用

注意: 浏览器:chrome。

【问题讨论】:

  • 你能提供最小的reproducible例子吗?
  • 也许您在请求之前有一些 if 条件。 if(cookies.yourSavedVariable){ doRequest() } first page 之类的东西使您的条件为真并且请求未执行
  • 如果请求完全相同,那么 chrome 可能会选择使用缓存响应而不是发出新请求。这可能就是您没有看到任何网络活动的原因。
  • 这应该会给你一些探索的提示:stackoverflow.com/questions/28752524/…

标签: javascript reactjs browser window


【解决方案1】:

使用 Memopromise 工具,它是处理异步进程的有效工具。

class MemoPromise {

 constructor(getPromise) {

   this.cache = {};

   this.getPromise = getPromise;

   this.request = this.request.bind(this);

 }

 request({ uniqueKey, ...rest }) {

   if (!uniqueKey) {

     return Promise.reject(new Error('Unique key not passed'));

   }

   if (this.cache[uniqueKey]) {

     return this.cache[uniqueKey];

   }

   const promise = this.getPromise(rest);

   this.cache[uniqueKey] = promise

     .then((res) => {

       delete this.cache[uniqueKey];

       return res;

     })

     .catch((err) => {

       delete this.cache[uniqueKey];

       throw err;

     });

   return this.cache[uniqueKey];

 }

}

在上面的例子中,我创建了一个 MemoPromise 类,它的实例化对象可以记住构造函数中传递的函数返回的 Promise,直到它们没有被解析或拒绝。

查看执行代码

const memoPromise = new MemoPromise(fn);

// invocation

const { request } = memoPromise;

request({ uniqueKey: url, apiType, url, payload });

// not required now

// fn({ apiType, url, payload });

在您的浏览器集成 Memopromise 类后,您的 API 请求可能不会遇到任何问题。它可以有效地处理您的重复请求。

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 2016-04-26
    • 2022-01-06
    • 2014-05-22
    • 2022-10-23
    • 1970-01-01
    • 2019-08-20
    • 2019-02-12
    • 2013-01-13
    相关资源
    最近更新 更多