如何在 useEffect 清理函数中取消所有订阅和异步任务

时间:2021-06-12 09:40:23

标签: reactjs react-native use-effect

<块引用>

无法对卸载的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请取消 useEffect 清理函数中的所有订阅和异步任务。

此处的页面包含一个可选择的 FlatList。但是,如果我太快地选择另一个元素(在加载整个 flatList 之前),则会出现上面的错误。我不确定应该在 useEffect 中放入哪个函数以及应该放入什么返回语句以使其清理(或让之前的 flatList 停止加载)。

错误特别指出了Item函数,如下代码所示(无关代码略过)

function ChampSelect({navigation, route}) {

    ...

    const Item = ({ item, onPress, weight, color}) => (
        <TouchableOpacity onPress={onPress}>
            <Image 
                source={require('../pictures/champions/' + item + '.png')}
                style= {[styles.image, color]}
            />
            <Text style={[styles.title, weight]}>
                {item}
            </Text>
        </TouchableOpacity>    
    )


    const renderItem = ({ item }) => {
        const fontWeight = item === selectedChamp ? 'bold' :'normal';
        const borderColor = item === selectedChamp ? '#6BDB5A' :'black'

        return (
            <Item 
                item={item}
                onPress={() => setSelectedChamp(item)}
                weight={{ fontWeight }}
                color = {{borderColor}}
            />
        )
    }

    ...

    return ( 

        ...
        
            <View style={{marginLeft: 48, marginTop: 40}}>
                <FlatList
                ListHeaderComponent={renderHeader}
                numColumns={3}
                horizontal={false}
                data={data}
                extraData={selectedChamp}
                renderItem={renderItem}
                keyExtractor={item => item}
                />
            </View>

        </View>
    )
    
}

任何帮助将不胜感激!

0 个答案:

没有答案