2016-08-21 128 views
2

当webview加载无效的url时,我应该设置哪个属性来显示错误视图?我尝试renderError,它触发控制台消息,但没有显示视图。React原生WebView加载错误处理

这里的代码:

<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> 
) 
} 

这里的屏幕截图

enter image description here

[更新]正如我重新加载清除错误,有这显示错误视图的临时状态。

enter image description here

+0

我们是否应该处理onError呢? – vijayst

+0

我不确定哪些属性是必需的。 – Klyment

回答

1

您可以使用onError道具如下图所示的错误后,渲染视图,并尝试处理不同的WebView错误。 renderError可以用来渲染视图,显示解决的WebView错误

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> 
    ); 
}} 

记住安装urijs并将其导入,从而使利用URI时。