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

Jos*_*ino 13 javascript reactjs react-native

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

我不知道我是怎么得到这个错误,因为我设置的状态DatacomponentDidMount.

我该如何解决这个问题?

Data

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;
Run Code Online (Sandbox Code Playgroud)

And*_*rew 6

在你的渲染功能中,你正在打电话this.setState({mounted:true}).来自React的组件文档:

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

这是关于渲染函数的React文档的链接.

  • 你的第一个建议是正确的,但你的第二个建议是不正确的.如果你不在箭头函数上提供括号,它将隐式返回.所以`.then(response => response.json())`与`.then(response => {return response.json();})相同` (2认同)