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

Android WebView中React应用无需刷新页面重新获取数据方案

解决方案

1. 在React应用中暴露全局更新方法

将数据更新逻辑封装后挂载到window对象,让WebView能直接调用:

function App() {
    const [sampleState, setSampleState] = React.useState(null)

    // 初始加载数据
    React.useEffect(() => {
        fetchAndUpdateState();
    }, [])

    // 封装数据更新逻辑
    const fetchAndUpdateState = async () => {
        const data = await fetchFromServer();
        setSampleState(data);
    }

    // 挂载全局方法供Native调用
    React.useEffect(() => {
        window.refreshSampleState = fetchAndUpdateState;
        // 组件卸载时清理全局方法
        return () => {
            delete window.refreshSampleState;
        }
    }, [])

    return (
        <p>{JSON.stringify(sampleState)}</p>
    );
}

2. 在Android侧触发数据更新

利用onNewIntent方法监听Activity被唤起的事件,调用React暴露的全局方法:

public class SampleWebActivity extends Activity {
    SampleWebInterface mWebInterface;
    WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        mWebView = new WebView(this);
        // 必须开启JavaScript支持
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        
        setContentView(mWebView);
    
        mWebInterface = new SampleWebInterface();
        mWebView.addJavascriptInterface(mWebInterface, "Native");
        //...
        mWebView.loadUrl("https://sample.com");
    }

    // 当Activity被重新唤起时触发
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (mWebView != null) {
            // 调用React的全局更新方法
            mWebView.evaluateJavascript("window.refreshSampleState();", null);
        }
    }
}

3. 关键注意点

  • 确保WebView开启JavaScript支持,否则无法执行JS代码。
  • 全局方法需在组件挂载完成后再挂载到window,避免Native调用时方法未定义。
  • 组件卸载时清理全局方法,防止内存泄漏。
  • 若需要接收更新结果,可为evaluateJavascript传入ValueCallback<String>参数处理返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:05:31