(React Native)警告:只能更新已安装或安装的组件

时间:2018-01-18 05:41:17

标签: react-native expo

需要帮助!我的代码出了什么问题?运行FadeImage后,我会收到此错误:

enter image description here

import React from 'react';
import { StyleSheet, Image } from 'react-native';

import * as Icons from '../constants/Icons';

export default class FadeImage extends React.Component {
  state = {index:0}

  constructor(props) {
    super(props);

    this.images = [
      Icons.BG_1,
      Icons.BG_2,
      Icons.BG_3,
      Icons.BG_4
    ]

    this.next = this.next.bind(this);
  }

  next() {
    setTimeout(() => {
      this.setState({index: (this.state.index+1) % 4});
      this.next();
    }, 3000);
  }

  componentDidMount() {
    this.next();
  }

  render() {
    return (
      <Image
        style={styles.backgroundImage}
        source={this.images[this.state.index]}/>
    )
  }
}

const styles = StyleSheet.create({
  backgroundImage: {
    flex: 1,
    alignSelf: 'stretch',
    width: null,
    justifyContent: 'center',
    alignItems: 'center'
  }
})

2 个答案:

答案 0 :(得分:1)

Ashish告诉警告的原因是在组件已经卸载时调用this.setState。要修复它,你应该取消超时。

以下是代码示例:

import React from 'react';
import { StyleSheet, Image } from 'react-native';

import * as Icons from '../constants/Icons';

export default class FadeImage extends React.Component {
  state = {index:0}

  constructor(props) {
    super(props);

    this.images = [
      Icons.BG_1,
      Icons.BG_2,
      Icons.BG_3,
      Icons.BG_4
    ]

    this.next = this.next.bind(this);
  }

  next() {
    this.timeoutId = setTimeout(() => {
      this.setState({index: (this.state.index+1) % 4});
      this.next();
    }, 3000);
  }

  componentDidMount() {
    this.next();
  }
  
  componentWillUnmount() {
    clearTimeout(this.timeoutId);
  }

  render() {
    return (
      <Image
        style={styles.backgroundImage}
        source={this.images[this.state.index]}/>
    )
  }
}

const styles = StyleSheet.create({
  backgroundImage: {
    flex: 1,
    alignSelf: 'stretch',
    width: null,
    justifyContent: 'center',
    alignItems: 'center'
  }
})

答案 1 :(得分:0)

组件销毁时需要取消超时。目前,即使卸载组件,也会执行setState。