使用clearTimeout和setTimeout的正确方法是什么?

问题描述 投票:1回答:1

当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>
        )
    }
}
reactjs react-native timer
1个回答
2
投票

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

handleLoading你可能需要在调用clearTimeout(this.timer)之前调用this.timer = setTimeout...

© www.soinside.com 2019 - 2024. All rights reserved.