2017-05-17 39 views
7

我是React的新手,但由於此錯誤而無法呈現我的應用。這似乎是我試圖呈現爲元素的數據不會呈現,因爲嘗試設置狀態時卸載?錯誤:試圖更新已經卸載(或未能安裝)的組件

我不知道我是如何得到這個錯誤的,因爲我在componentdidmount中設置了Data的狀態,我該如何解決這個問題?

error: attempted to update component that has already been unmounted (or failed to mount)文本。

class Profile extends React.PureComponent { 
    static propTypes = { 
    navigation: PropTypes.object, 
    handleLogout: PropTypes.func, 
    user: PropTypes.object, 
    }; 

    static navigationOptions = { 
    headerVisible: true, 
    title: 'Profile', 
    }; 

constructor(props) { 
    super(props); 

    this.state = { 
    data: [], 
    loading: true 

    }; 
    } 

componentDidMount() { 



    fetch("http://10.0.2.2:8080/combined", { method: 'get' }) 
    .then(response => response.json()) 
    .then(data => { 
     this.setState({data: data,}); 

    }) 
    .catch(function(err) { 
    // 
    }) 
} 





    render() { 


    const { user } = this.props; 
    let email; 


    if (user) { 
     email = user.rows[0].ACCTNO; 
    } 
    return (
     <ContentWrapper> 
     <View style={styles.container}> 
      <Image style={styles.header} source={images.profileHeader} /> 
      <View style={styles.body}> 
      <Avatar email={email} style={styles.avatar} /> 
      { 
    this.state.data.map(function(rows, i){ 
     this.setState({mounted: true}); 

    return(
     <View key={i}> 
     <Text>{rows.FIRSTNAME}</Text> 
     </View> 
    ); 
    }) 
}   <Text style={styles.email}>{_.capitalize(email)}</Text> 

      <Button 
       title="Log out" 
       icon={{ name: 'logout-variant', type: 'material-community' }} 
       onPress={this.logout} 
       style={styles.logoutButton} 
      /> 
      </View> 
     </View> 
     </ContentWrapper> 
    ); 
    } 
} 

export default Profile; 
+1

您的地圖功能是錯誤發生的原因。你在render()中調用setState。 –

回答

4

在你的渲染函數中,你打電話給this.setState({mounted:true})。從陣營的組件文檔:

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser.

這裏的link對渲染功能的陣營文檔。

+2

你的第一個建議是正確的,但你的第二個不是。如果你不提供括號的箭頭功能,它會隱式返回。所以'.then(response => response.json())'和'.then是一樣的(response => {response;>; })' –

+0

@MattAft @Andrew這是什麼原因錯誤?對我來說顯示「嘗試更新已經卸載(或掛載失敗)的組件'SmallSpinner'」。但我沒有在渲染函數中做setState – Dramorian

相關問題