【问题标题】:componentDidMount is rendering continuously in React NativecomponentDidMount 在 React Native 中持续渲染
【发布时间】:2019-02-18 05:54:22
【问题描述】:

我的目标是添加一个带有进度条的启动画面,所以我使用react-native-progress 作为进度条库。并通过执行登录检查将屏幕添加为初始路线。

我使用的是redux,所以我创建了一个动作来执行进度条中的进度过程,动作代码如下:

 export const progressBarLevel = () => {
return (dispatch) => {
    this.progress = 0;
    dispatch({ type: PROGRESS, payload: 0 });
    setTimeout(() => {
        this.indeterminate = false;
        setInterval(() => {
            this.progress += Math.random()/5;
            if(this.progress > 1){
                this.progress = 1;
            }
            return dispatch({ type: PROGRESS, payload: this.progress });
        },250)
    },500)
}
}   

然后,将其连接到减速器以保存进度。然后将那条进度状态带入闪屏,通过 props 连接起来。

现在发生的事情是,我从 componentDidMount() 调用了进度操作和登录检查操作,因为两者都正常工作。但是由于某种原因,进度操作无限运行,因为我已经控制台记录了该操作,“return dispatch({ type: PROGRESS, payload: this.progress });”这将被无限调度。我找不到错误的根源。

我的组件DidMount():

 componentWillMount() {
    this.props.loginCheck(() => {
        this.setState({ isUserAvailble: true})
    })
   this.props.progressBarLevel();
}

我的进度条代码:

<View style={{ alignItems: 'center' }}>
                    <ProgressBar progress={this.props.progressed} width={200} borderColor="#fff" color="#fff"/>
                </View>

我无法理解问题,如何停止连续渲染。我什至使用 componentWillMount 尝试过这个,我也得到了连续的动作调度。

请指导。

更新

将变量分配给 setInterval 然后使用 clearInterval 调用它解决了问题

更新代码

this.progress = 0;
    dispatch({ type: PROGRESS, payload: 0 });
    setTimeout(() => {
        this.indeterminate = false;
       const interval = setInterval(() => {
            this.progress += Math.random()/5;
            if(this.progress > 1){
                this.progress = 1;
                clearInterval(interval);
            }
            return dispatch({ type: PROGRESS, payload: this.progress });
        },250)
    },500)

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    查看您的代码,我认为问题出在动作调度中的 setInterval 方法。

    它没有被清除并更新您的状态树。

    编辑 1: 您可以尝试以下代码以获得明确的间隔。

    this.interval = setInterval(() => {
                this.progress += Math.random()/5;
                if(this.progress > 1){
                    this.progress = 1;
                }
                if(this.progress === 1 && this.interval){
              clearInterval(this.interval);
    }
                return dispatch({ type: PROGRESS, payload: this.progress });
            },250)
    

    【讨论】:

    • 我已将一个变量分配给 setInterval 并使用 clearInterval(variable) 调用。哪个停止了 setInterval。感谢您的建议!
    • 如果解决了您的问题,请采纳。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 2019-06-18
    • 2020-11-14
    • 1970-01-01
    • 2021-10-28
    • 2020-05-31
    相关资源
    最近更新 更多