使用clearTimeout和setTimeout的正确方法?

时间:2018-09-06 22:50:43

标签: reactjs react-native timer

运行setTimeout函数时,每当我离开屏幕时,都会收到内存泄漏错误。我知道我应该清除计时器,但它对我不起作用。我在某处缺少某物...

这是我的代码。我删除了许多与该问题无关的内容,因此请您谅解某些语法是否错误或是否没有结束标记。

谢谢!

export default class EditContent extends Component {
    timer;

    constructor(props) {
        super(props);

        this.state = {           
            isLoading: false,
            buttonMessage: 'Save Changes'
        }

    }

    componentWillMount(){
        this.timer
    }

    componentWillUnmount() {
        clearTimeout(this.timer)
    }


    handleLoading(bool) {
        this.setState({
            loading: bool,
            buttonMessage: !bool && 'Changes Saved!'
        })
        this.timer = setTimeout(() => {
            this.setState({ buttonMessage: 'Save Changes' })
        }, 5000);

    }



    handleBack() {
        clearTimeout(this.timer)
        this.props.navigation.goBack(null)
    }

    handleSaveChanges() {
        const { goBack } = this.props.navigation;
        this.handleLoading(true)

        this.props.updateDeliveryPickup()
            .then((resp) => {
                this.handleLoading(false)
                console.log('resp', resp)
            })
    }

    render() {
        const { pickup } = this.props


        return (

            <View style={styles.editWrapper}>


                <View style={styles.userStoreHeader}>
                    <Text>My Account</Text>
                </View>

                <Subheader onPressBack={() => this.handleBack()} />

                <View style={styles.summaryContainer}>

                    <SettingsButton
                        onPress={() => this.handleSaveChanges()}
                        buttonMessage={buttonMessage}
                    />

                </View>
            </View>
        )
    }
}

1 个答案:

答案 0 :(得分:2)

首先onPress={() => this.handleSaveChanges()}是一个不好的做法,它将为组件的每个渲染创建一个新函数,您应该直接编写onPress={this.handleSaveChanges},同样可以应用于onPressBack<Subheader onPressBack={this.handleBack} />

handleLoading中,您可能需要先致电clearTimeout(this.timer),然后再致电this.timer = setTimeout...

相关问题