如何在componentWillUnmount方法中取消所有订阅和异步任务

时间:2019-09-14 13:30:47

标签: javascript reactjs react-native

大家好,我目前正在使用React-Native开发一个应用程序,并且我的HomeScreen内有一个轮播。有一个错误不允许我通过滑动来打开DrawerNavigator,除非我单击标题上的汉堡包图标,然后可以通过滑动来打开抽屉,但是之后弹出黄色警告屏幕,提示: 警告:无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,请取消componentWillUnmount方法中的所有订阅和异步任务

The warning screen

我尝试使用AbortController,但是要么我以错误的方式使用了它,要么不起作用。

import * as React from 'react';
import {
  StyleSheet,
  ScrollView,
  Dimensions,
  Image,
  TouchableOpacity,
} from 'react-native';

const DEVICE_WIDTH = Dimensions.get('window').width;

class Carousel extends React.Component {
  scrollRef = React.createRef();
  constructor(props) {
    super(props);

    this.state = {
      selectedIndex: 0,
    };
    this.scrollRef = React.createRef();
  }

  componentDidMount = () => {
    setInterval(() => {
      this.setState(
        prev => ({
          selectedIndex:
            prev.selectedIndex ===
            this.props.images.length - 1
              ? 0
              : prev.selectedIndex + 1,
        }),
        () => {
          this.scrollRef.current.scrollTo({
            animated: true,
            x: DEVICE_WIDTH * this.state.selectedIndex,
            y: 0,
          });
        }
      );
    }, 4000);
  };

  setSelectedIndex = event => {
    const contentOffset = event.nativeEvent.contentOffset;
    const viewSize = event.nativeEvent.layoutMeasurement;
    const selectedIndex = Math.floor(
      contentOffset.x / viewSize.width
    );
    this.setState({ selectedIndex });
  };

  render() {
    const { images } = this.props;
    return (
      <TouchableOpacity activeOpacity={0.5}>
        <ScrollView
          horizontal
          pagingEnabled
          onMomentumScrollEnd={this.setSelectedIndex}
          ref={this.scrollRef}
        >
          {images.map(image => (
            <Image
              style={styles.backgroundImage}
              source={{ uri: image.i }}
              key={image.key}
            />
          ))}
        </ScrollView>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  backgroundImage: {
    resizeMode: 'cover',
    width: Dimensions.get('window').width,
  },
});

export default Carousel;

0 个答案:

没有答案