You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native WebView返回上一页时页面重复加载问题求助

解决React Native WebView返回页面重新加载的问题

问题核心是WebView默认的导航缓存策略导致返回时重新拉取资源,通过调整以下WebView属性可以解决:

  • 启用DOM存储:动态网站通常依赖DOM Storage保存页面状态,开启domStorageEnabled能让页面状态在导航时保留。
  • 配置缓存模式:设置cacheMode为'LOAD_CACHE_ELSE_NETWORK',优先使用本地缓存,缓存不存在时再请求网络,避免返回时重新加载全部资源。
  • 优化加载状态:补充加载状态控制,提升用户体验。

修改后的完整代码:

import { WebView } from 'react-native-webview';
import { StatusBar, View, StyleSheet } from 'react-native';
import React, { useRef, useState, useCallback, useEffect } from "react";
import { BackHandler, ActivityIndicator } from "react-native";

const App = () => {
  const styles = StyleSheet.create({
    activityIndicatorStyle: {
      flex: 1,
      justifyContent: 'center',
    },
  });

  const ActivityIndicatorElement = () => {
    return (
      <ActivityIndicator
        color="#009688"
        size="large"
        style={styles.activityIndicatorStyle}
      />
    );
  };

  const webView = useRef<WebView>(null);
  const [canGoBack, setCanGoBack] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  const handleBack = useCallback(() => {
    if (canGoBack && webView.current) {
      webView.current.goBack();
      return true;
    }
    return false;
  }, [canGoBack]);

  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", handleBack);
    return () => {
      BackHandler.removeEventListener("hardwareBackPress", handleBack);
    };
  }, [handleBack]);

  return (
    <>
      <StatusBar barStyle="dark-content" backgroundColor="#ffffff"/>
      {isLoading && <ActivityIndicatorElement />}
      <WebView
        originWhitelist={['*']} 
        javaScriptEnabled={true} 
        geolocationEnabled={true}
        domStorageEnabled={true} // 启用DOM存储,保留页面状态
        cacheMode='LOAD_CACHE_ELSE_NETWORK' // 优先使用缓存,无缓存再请求网络
        ref={webView}
        source={{ uri: "https://pharmogram.in/" }}
        onLoadProgress={(event) => {
          setCanGoBack(event.nativeEvent.canGoBack);
          setIsLoading(event.nativeEvent.progress < 1);
        }}
        onLoadEnd={() => setIsLoading(false)}
        style={{ display: isLoading ? 'none' : 'flex' }}
      />
    </>
  );
}

export default App;

额外说明:

  • cacheMode可选值说明:
    • 'LOAD_DEFAULT':默认策略,根据HTTP缓存头决定是否使用缓存
    • 'LOAD_CACHE_ELSE_NETWORK':优先用缓存,无缓存再请求网络,适合需要保留页面状态的场景
    • 'LOAD_NO_CACHE':完全不使用缓存(不推荐)
  • 如果网站本身设置了禁止缓存的HTTP头,可能需要后端配合调整缓存策略,但前端先尝试上述配置通常能解决大部分问题。

内容的提问来源于stack exchange,提问作者Rahul Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 23:31:09