I'm new to React, I'm having trouble rendering my app due to this error. It's seems the data that I'm trying to render as elements won't render due to trying to set state when unmounted?
I'm not sure how I'm getting this error, as I'm setting the state of Data
in componentDidMount
.
How can I fix this issue?
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;
In your render function, you're calling this.setState({mounted:true})
. From React's component documentation:
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.
Here's the link to the React documentation on the render function.
My problem is I forget
import React from 'react'
in my .jsx
file, since I thought importing React is not needed in functional component.
There is another way this error can occur...thinking that props are individual arguments (props is actually a single argument)
import React from 'react';
const Posts = posts => { // WRONG
const Posts = ({posts}) => { // RIGHT
const renderPosts = () => {
return posts.map(post => <div>{post.title}</div>);
};
return <div>{renderPosts()}</div>;
};
My problem was in Sider, Then inside Link tag I did misspell instead of /location I wrote /locaion .
<Menu.Item key="2">
<Icon type="settings" />
<span><Link style={styles.linkStyle} to="/locations">Locations</Link></span>
</Menu.Item>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.