(React Native) Предупреждение: можно обновить только смонтированный или смонтированный компонент.

Нужна помощь! Что не так с моим кодом? После запуска FadeImage я получу эту ошибку:

введите здесь описание изображения

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'
  }
})

person ruin3936    schedule 18.01.2018    source источник


Ответы (2)


Как сказал Ашиш, причиной предупреждения является вызов this.setState, когда компонент уже размонтирован. Чтобы исправить это, вы должны просто отменить тайм-аут.

Here is code example:

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'
  }
})

person Slowyn    schedule 18.01.2018

Вам нужно отменить тайм-аут, когда компонент уничтожен. В настоящее время setState выполняется, даже когда компонент выгружен.

person Ashish Prakash    schedule 18.01.2018