2016-08-21 95 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時。