【问题标题】:FlatList onPress function rerender causes lag after usestate updateFlatList onPress 函数重新渲染导致 usestate 更新后滞后
【发布时间】:2021-02-03 18:08:43
【问题描述】:

所以我们有一个包含大约 200/300 个按钮的平面列表 这些按钮获得了一个功能,该功能在 5 次点击后显示广告。 所以我们使用 useState 来统计点击次数。

但是.. 因为我们更新了函数内部的计数,所以它再次调用它自身并重新呈现所有平面列表项/按钮并导致滞后/延迟。

“滞后是什么意思?” 例如,通常您可以点击按钮进行垃圾邮件,一切都很好,但是当 setCount(prev => prev +1) 未注释时,它只会慢慢冻结并落后

代码

import React, {useCallback, useState} from 'react';
import {TouchableOpacity,FlatList, View, Text} from 'react-native';

const data = ['IMAGINE 200 items here.']

const test = () => {
    const [count, setCount] = useState(0);

    const TestFunction = useCallback(async () => {
        setCount(prev => prev + 1);

        if (count === 5) {
            /*for example show a add*/
            showAd();
        }
    }, [count]);


    return (
        <View>
            <FlatList data={data} renderItem={() => React.useMemo(<TouchableOpacity onPress={TestFunction}>
                <Text>Test</Text>
            </TouchableOpacity>)}>

            </FlatList>
        </View>
    );
};


const showAd = () => {
    /*for example show a add*/
};

【问题讨论】:

    标签: reactjs react-native react-functional-component


    【解决方案1】:

    我认为您应该将 TestFunction 分成两部分

    const addClick = useCallback(() => { setCount(prev => prev + 1) }, []) 
    // this doesn't need count dependency
    

    const showAdOnCountThreshold = useEffect(() => { if (count === 5) showAd() }, [count] 
    // this gets called after updating the count
    

    另外,您的 React.memo 没有做任何事情,因为它没有设置依赖项。但是既然你有 addClick 永远不会改变,那么 Touchables 就没有理由改变(就道具变化而言)。

    所以你可以这样做:

    const renderClickCountButton = React.useCallback(() => (
     <TouchableOpacity onPress={addClick}>...</TouchableOpacity>
    ), [addClick])
    

    然后

    <FlatList renderItem={renderClickCountButton}
    

    【讨论】:

      猜你喜欢
      • 2019-10-17
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 2021-07-15
      • 2020-01-13
      • 2020-07-18
      相关资源
      最近更新 更多