React Native WebView Loading Error Handling

牧云@^-^@ 提交于 2020-01-03 15:22:11

问题


When the webview loads an invalid url, which property should I set to display an error view? I try renderError, it triggers the console message but did not display the view.

here's the code:

<View style={styles.webview_body}>
  <WebView
   source={{uri:this.props.url}}
   onNavigationStateChange={this.onNavigationStateChange.bind(this)}
   renderError={this.loadError.bind(this)}
 />
</View>

//the fucntion which display the error message
loadError(){
console.log('loaded');
return (
  <View>
    <Text>
    something goes wrong.
    </Text>
  </View>
)
}

here's the screenshots

[Update] As I reload to clear the error, there's a temporary state which display the error view.


回答1:


You could use the onError prop as shown below to render a view after an error and also to try handling the different WebView errors. renderError can be used to render a view that shows when resolving the WebView errors

onError={ (e) => {
    let uri = new URI(this.props.url);
    let host = uri.host();
    let insecureHosts = [-1004, -6, -1202];//all error codes as displayed on your console 
    if(e){
        //Handles NSURLErrorDomain in iOS and net:ERR_CONNECTION_REFUSED in Android
        if(insecureHosts.indexOf(e.nativeEvent.code) !== -1){
            this.setState({url: `http://${host}`});
            }
        //Handles Name resolution errors by redirecting to Google
        else if(e.nativeEvent.code === -1003 ||  e.nativeEvent.code === -2){
            this.setState({url: `https://www.google.com/#q=${host}`});
        }
    } else {
    //loads the error view only after the resolving of the above errors has failed
        return(
            <View>
                Error occurred while loading the page.
            </View>
            );
        }}}
renderError={(e) => {
//Renders this view while resolving the error 
    return(
        <View>
            <ActivityIndicator
            animating={ true }
            color='#84888d'
            size='large'
            hidesWhenStopped={true}
            style={{alignItems:'center', justifyContent:'center', padding:30, flex: 1}}/>
            </View>
    );
}}

Remember to install urijs and import it so as to make use of URI.



来源:https://stackoverflow.com/questions/39063183/react-native-webview-loading-error-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!