首页  >  问答  >  正文

React Native - 获取调用缓存

我正在用 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粉585541766P粉585541766334 天前621

全部回复(2)我来回复

  • P粉548512637

    P粉5485126372023-10-22 21:31:24

    Manosim 的答案对我来说不起作用,但让我走上了一条确实有效的解决方案:

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

    这解决了问题。

    回复
    0
  • P粉738248522

    P粉7382485222023-10-22 12:07:09

    您可以设置标头以防止请求被缓存。 下面的例子:

    return fetch(url, {
      headers: {
        'Cache-Control': 'no-cache'
      }
    }).then(function (res) {
      return res.json();
    }).catch(function(error) {
      console.warn('Request Failed: ', error);
    });

    回复
    0
  • 取消回复