错误:尝试更新已卸载(或无法装入)的组件

时间:2017-05-17 17:23:29

标签: javascript reactjs react-native

我是React的新手,由于此错误,我无法渲染我的应用。看起来我试图呈现为元素的数据由于尝试在卸载时设置状态而无法呈现?

我不确定我是如何收到此错误的,因为我在Data中设置了componentDidMount状态。

如何解决此问题?

  

错误:尝试更新已卸载(或无法装入)的组件

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;

4 个答案:

答案 0 :(得分:6)

在渲染功能中,您正在调用1000。来自React的组件文档:

  

render()函数应该是纯的,这意味着它不会修改组件状态,每次调用它都会返回相同的结果,并且它不直接与浏览器交互。

这里是关于渲染功能的React文档的link

答案 1 :(得分:2)

我的问题是我忘了

import React from 'react'

在我的.jsx文件中,因为我认为在功能组件中不需要导入React。

答案 2 :(得分:1)

还有另一种方法可以发生此错误...认为道具是个别参数(道具实际上是一个参数)

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

答案 3 :(得分:0)

我的问题出在Sider,然后在Link标签里面我拼错了而不是/ location我写了/ locaion。

 <Menu.Item key="2">
      <Icon type="settings" />
      <span><Link style={styles.linkStyle} to="/locations">Locations</Link></span>
    </Menu.Item>