簡體   English   中英

當我更新此函數內的狀態時,油門函數不起作用

[英]throttle function does not work when i update state inside this function

下面是代碼。 runonce函數不能正常工作(它應該只在 3000 毫秒內運行一次)但是如果我不更新狀態那么它工作正常。

const HomeScreen = ({ navigation }) => {
    const [count, setCount] = useState(1)

    function runOnce(func, delay) {
        let timer = null;
        return function (...args) {
            if (!timer) {
                timer = setTimeout(() => {
                    timer = null;
                }, delay);
                return func(...args);
            }
        };
    }

    const handleButtonClick = runOnce(() => {
        console.log("This function will run only once in 3000 milliseconds");
        //here if i don't update below state then console runs only once in 3000ms 
        // but if i update state then it runs whenever i click button 
        setCount(prev => prev + 1)
    }, 3000);



    return <SafeAreaView style={{ flex: 1 }}>
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text style={{ margin: 10, color: 'red', fontSize: 24 }}>{count}</Text>
            <TouchableOpacity style={{ marginTop: 10 }} onPress={() => handleButtonClick()}>
                <Text style={{ color: 'blue' }}>Increment Count</Text>
            </TouchableOpacity>
        </View>
    </SafeAreaView>
}

正如預期的那樣,runonce 中的函數應該每 3000 毫秒只運行一次,不管你點擊多少次

更新狀態時,您的函數會重新運行並重建您的點擊處理程序,使其成為每次渲染時的新函數,每次都有一個新的計時器。

為避免這種情況,請使用 useCallback 記住函數。

const handleButtonClick = useCallback(() => runOnce(() => {
        console.log("This function will run only once in 3000 milliseconds");
        //here if i don't update below state then console runs only once in 3000ms 
        // but if i update state then it runs whenever i click button 
        setCount(prev => prev + 1)
    }, 3000), []);

我可以看到您已經創建了自己的函數來執行間隔突破或延遲以運行函數。 但是 Javascript 已經借助這兩個函數幫助我們做到這一點。

setInterval() - 以毫秒為單位以給定的時間間隔運行函數。 ( https://www.w3schools.com/jsref/met_win_setinterval.asp )

setTimeout() - 在以毫秒為單位的特定時間延遲后運行函數。 ( https://www.w3schools.com/jsref/met_win_settimeout.asp )

我希望這可以幫助您減少您擁有的冗余代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM