【问题标题】:How to reload react-native-webview content on appState change如何在 appState 更改时重新加载 react-native-webview 内容
【发布时间】:2021-10-13 02:12:00
【问题描述】:

我的应用中有一个网络视图。我为它设置了 onNavigationStateChange 道具来处理点击 webview 上的任何链接并将用户导航到浏览器。 问题是当用户在浏览器上按 BackAndroid 时返回我的应用程序 webview 内容没有显示并且屏幕是空的和白色的。 对于这个问题,我尝试使用 appState 并在返回我的应用程序后处理其更改以重新加载 webview,但收到此错误

这是我的代码:

function Screen(props) {
  const [appState, setAppState] = React.useState(AppState.currentState);
  let webview = React.useRef(null);
  React.useEffect(() => {
    AppState.addEventListener('change', handleAppStateChange);
    return () => AppState.removeEventListener('change', handleAppStateChange);
  }, []);
  function backHandler() {
    popScreen(Screens.About);
    return true;
  }
  function handleAppStateChange(nextAppState) {
    if (nextAppState === 'active') {
      webview.reload();
    }
    setAppState(nextAppState);
  }
  const WebView = require('react-native-webview').default;
  return (
      <View style={styles.container}>
        <View style={styles.web}>
          <WebView
            ref={ref => {
              webview = ref;
            }}
            source={{uri: props.link}}
            androidHardwareAccelerationDisabled={true} // for prevent crash
            startInLoadingState={true}
            onNavigationStateChange={event => {
              if (event.url !== props.link) {
                webview.stopLoading();
                Linking.openURL(event.url);
              }
            }}
            renderLoading={() => (
              <CircleLoading
                containerStyle={[styles.loading]}
                renderLoading={true}
              />
            )}
          />
        </View>
      </View>
  );
}

谢谢。

【问题讨论】:

    标签: android react-native webview react-native-webview


    【解决方案1】:

    试试这个方法:

    const [appState, setAppState] = React.useState(AppState.currentState);
      const webview = React.useRef(null);
      React.useEffect(() => {
        AppState.addEventListener('change', handleAppStateChange);
        return () => AppState.removeEventListener('change', handleAppStateChange);
      }, [webview.current]);//    <---- CHANGED
      function backHandler() {
        popScreen(Screens.About);
        return true;
      }
      function handleAppStateChange(nextAppState) {
        if (nextAppState === 'active') {
          webview.current.reload(); //     <---- CHANGED
        }
        setAppState(nextAppState);
      }
      const WebView = require('react-native-webview').default; //  <---- remove it and import it at top of file
      return (
          <View style={styles.container}>
            <View style={styles.web}>
              <WebView
                ref={webview} //    <---- CHANGED
                ..
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-11
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 2012-11-08
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多