React Native - 取得呼叫緩存
P粉585541766
P粉585541766 2023-10-21 23:44:23
0
2
616

我正在用 React Native 建立一個應用程序,它進行依賴伺服器的最新資訊的獲取呼叫。我注意到它似乎緩存了回應,如果我再次運行該 fetch 調用,它會返回快取的回應,而不是來自伺服器的新資訊。

我的功能如下:

goToAll() {
  AsyncStorage.getItem('FBId')
    .then((value) => {
      api.loadCurrentUser(value)
        .then((res) => {
          api.loadContent(res['RegisteredUser']['id'])
            .then((res2) => {
              console.log(res2);
              this.props.navigator.push({
                component: ContentList,
                title: 'All',
                passProps: {
              content: res2,
            user: res['RegisteredUser']['id']
          }
        })
      });
    });
  })
  .catch((error) => {console.log(error);})
  .done();
}

我呼叫的 api.js 函數如下:

loadContent(userid){
  let url = `http://####.com/api/loadContent?User_id=${userid}`;
  return fetch(url).then((response) => response.json());
}


#
P粉585541766
P粉585541766

全部回覆(2)
P粉548512637

Manosim 的答案對我來說不起作用,但讓我走上了一條確實有效的解決方案:

fetch(url, {
  headers: {
    'Cache-Control': 'no-cache, no-store, must-revalidate',
    'Pragma': 'no-cache',
    'Expires': 0
  }
})

這解決了問題。

P粉738248522

您可以設定標頭以防止請求被快取。 下面的例子:

return fetch(url, {
  headers: {
    'Cache-Control': 'no-cache'
  }
}).then(function (res) {
  return res.json();
}).catch(function(error) {
  console.warn('Request Failed: ', error);
});
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!