简体   繁体   English

我如何在反应中取消订阅

[英]how can I cancel subscriptions in react

I got this warning on my code to display a carousel.我在代码中收到此警告以显示轮播。 Warning: Can't perform a React state update on an unmounted component.警告:无法对卸载的组件执行 React 状态更新。 This is a no-op, but it indicates a memory leak in your application.这是一个空操作,但它表明您的应用程序中存在内存泄漏。 To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.要修复,请取消 componentWillUnmount 方法中的所有订阅和异步任务。

I tried to unsubscribe with componentWillUnmount but the warning persists.我尝试使用 componentWillUnmount 取消订阅,但警告仍然存在。 Below is my code.下面是我的代码。

    constructor(props) {
        super(props);
        const idxStart = 0;
        this.state = {
            current: idxStart,
            prev: this.getPrevIndex(idxStart),
            next: this.getNextIndex(idxStart),
            Text: Text
        };
        // To disable autoplay, change to false 
        this.autoPlay = true;
    }

    getPrevIndex = (idx) => {
        if (idx <= 0) {
            return pics.length - 1;
        }
        return idx - 1;
    }

    getNextIndex = (idx) => {
        if (idx >= pics.length - 1) {
            return 0;
        }
        return idx + 1;
    }

    setIndexes = (idx, dir) => {
        this.setState({
            current: idx,
            prev: this.getPrevIndex(idx),
            next: this.getNextIndex(idx),
            dir
        });
    }

    transitionSlide = (direction) => {
        if (this.moving) return;
        // start animation
        this.setState({
            dir: direction,
            move: true
        });
        this.moving = true;

        //stop animation
        setTimeout(() => {
            this.setState({
                move: false
            });
            if (direction === 'next') {
                this.setIndexes(this.getNextIndex(this.state.current), 'next');
            } else {
                this.setIndexes(this.getPrevIndex(this.state.current), 'prev');
            }
            this.moving = false;
        }, 500);

    }

    componentDidMount() {
        if (this.autoPlay) {
            setInterval(this.handleNext, 6000);
        }
    }

    componentWillUnmount() {
        this.autoplay === false
        clearInterval(setInterval(this.handleNext, 6000));
        clearTimeout(setTimeout(() => {
            this.setState({
                move: false
            });
            if (direction === 'next') {
                this.setIndexes(this.getNextIndex(this.state.current), 'next');
            } else {
                this.setIndexes(this.getPrevIndex(this.state.current), 'prev');
            }
        }, 500))
    }

    handlePrev = () => {
        this.transitionSlide('prev');
    }

    handleNext = () => {
        this.transitionSlide('next');
    }```

I have tried to fix this perhaps there is something I am not doing right.

clearInterval(setInterval(this.handleNext, 6000)); schedules a new interval timer and immediately cancels it, leaving your old interval timer still running.安排一个新的间隔计时器并立即取消它,让旧的间隔计时器仍在运行。

What you need to do is remember the timer handle you got from setInterval in componentDidMount , probably as an instance property, and use that:您需要做的是记住从componentDidMount setInterval获得的计时器句柄,可能作为实例属性,并使用它:

componentDidMount() {
    if (this.autoPlay) {
        this.intervalHandle = setInterval(this.handleNext, 6000);
    }
}

componentWillUnmount() {
    if (this.intervalHandle) {
        clearInterval(this.intervalHandle);
        this.intervalHandle = 0; // Not strictly necessary, but I like to do
                                 // this so I know looking at the handle whether
                                 // I've cancelled it. (The value from
                                 // `setInterval` will never be 0.)
    }
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React 中取消 UseEffect 中的所有订阅 - How to cancel all subscriptions inside UseEffect in React 我如何在反应中取消setTimeout时间 - How can I cancel the setTimeout time in react 如何解决React App中的内存泄漏和取消所有订阅错误? - How to Resolve Memory Leak and Cancel All Subscriptions Error in React App? 如何取消取消所有订阅和异步任务? - How to cancel cancel all subscriptions and asynchronous tasks? React 警告:无法对卸载的组件执行 React 状态更新。 要修复,请取消所有订阅 - React Warning: Can't perform a React state update on an unmounted component. To fix, cancel all subscriptions 在 componentWillUnmount 方法中取消所有订阅和异步,如何? - Cancel All Subscriptions and Asyncs in the componentWillUnmount Method, how? 条纹订阅 - 如何格式化 cancel_at 日期 - Stripe subscriptions - how to format cancel_at date 如果视图在带有 react-router-dom 的 React 路由中,我如何取消重新渲染视图 - How can I cancel re-render view if view is in Route on React with react-router-dom React - 修复、取消 useEffect 清理中的所有订阅和异步任务 function - React - To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function 如果卸载/重用React组件,如何在Promise中取消下一个&#39;then&#39;? - How can I cancel the next 'then' in a Promise when a React component is unmounted/reused?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM