You need to enable JavaScript to run this app. React Native RefreshControl绑定ScrollView嵌套FlatList下拉刷新数据重复
优惠活动
大模型
产品
解决方案
定价
更多

React Native RefreshControl绑定ScrollView嵌套FlatList下拉刷新数据重复

问题根因
  • 数据更新逻辑无差别追加:searchApi 中固定执行 this.setState({results: [...this.state.results, response.data]}),无论当前是初次加载还是下拉刷新场景,都会把新拿到的接口数据往旧的results数组末尾拼接。下拉刷新的逻辑预期是用最新的全量返回数据覆盖旧数据,而非叠加,每次触发就拼接一次相同的返回结果,自然会造成列表内容反复叠加。
  • 状态初始化不全:初始state中没有定义results的默认值,首次调用接口时容易触发undefined相关的异常,也会让拼接逻辑出现不可预期的结果。
  • 组件嵌套违反RN设计规范:FlatList本身是具备完整滚动能力的虚拟列表组件,被外层ScrollView包裹后,其虚拟渲染能力会完全失效(大数据量下会出现明显的卡顿、掉帧),同时下拉刷新事件被外层ScrollView接管,也会进一步放大数据更新逻辑的问题。
修复方案

1. 修正数据更新逻辑,区分刷新与普通加载场景

给searchApi增加场景标记,下拉刷新触发时直接用接口返回的新数据替换results,而非拼接;同时补上缺失的state初始值,避免运行时异常。

// 补充缺失的state初始值
state = {
    refreshing: false,
    results: [],
}

searchApi = async(isRefresh = false) => {
    const response = await axios.get('http://73udkYid.ngrok.io/api/v1/products',{
        headers: {
            "x-auth-token":"eyJfaWQiOiI1ZdfjzZmM4YjIwYjBjZDQyMmJkNzUiLCJpYXQiOjE2MD"
        }
    });
    // 下拉刷新时直接覆盖旧数据,普通加载时保留追加逻辑
    if (isRefresh) {
        this.setState({ results: response.data });
    } else {
        this.setState({ results: [...this.state.results, response.data] });
    }
}

// 触发刷新时传入标记,请求结束无论成功失败都关闭刷新状态
_onRefresh = () => {
    this.setState({refreshing: true});
    this.searchApi(true).finally(() => {
        this.setState({refreshing: false});
    });
}

2. 调整组件结构,去掉外层冗余ScrollView

直接把RefreshControl绑定在FlatList自身的refreshControl属性上,移除外层包裹的ScrollView,既恢复FlatList的虚拟列表渲染能力,也让滚动事件的处理符合组件的原生设计逻辑:

render() {
    let finalGames = [];
    this.state.results.forEach(obj => {
        Object.keys(obj).forEach(key => {
            finalGames.push(obj[key]);
        });
    });

    return (
        <FlatList 
            style={{flex: 1, backgroundColor: 'white'}}
            data={finalGames}
            keyExtractor={(item, index) => index.toString()}
            // RefreshControl直接绑定在FlatList上
            refreshControl={
                <RefreshControl 
                    refreshing={this.state.refreshing}
                    onRefresh={this._onRefresh}
                />
            }
            renderItem={({item: itemData}) => {
                if(itemData.empty) {
                    return <View style={[styles.item, styles.itemInvisible]}/>
                }
                return (
                    <View style={{ flex: 1, margin: 4 }}>
                        <View style={styles.item}> 
                            <TouchableOpacity 
                                onPress={() => {
                                    this.setState({ viewController: this.state.viewController + 1 })
                                    this.props.navigation.navigate("ProductDetail", {
                                        itemDataDetail: itemData,
                                        businessname: this.props.navigation.state.params.businessname,
                                        viewController: this.state.viewController,
                                    })
                                }}>
                                <View>
                                    <ImageBackground 
                                        source={{ uri: itemData.photo }}
                                        style={{ width:'100%',aspectRatio: 1, borderRadius: 15, borderWidth:1, borderColor:"#FAFAFA", overflow: 'hidden'}}>
                                    </ImageBackground>
                                    <View style={{ margin: 5 }}>
                                        <Text style={{color: '#2E2E2E', fontWeight:"bold"}} numberOfLines={1}>{itemData.item}</Text>
                                        <Text style={{color: '#2E2E2E', fontSize: 12, fontWeight:"normal", alignSelf: 'flex-start'}} numberOfLines={1}>Available now | Sold out</Text>
                                        <Text style={{color: 'white', fontSize: 18, fontWeight:"bold", backgroundColor:"#DE1F38", alignSelf: 'flex-start', paddingHorizontal: 10,paddingVertical:2,borderRadius: 8,overflow: 'hidden', marginTop: 5}} numberOfLines={1}>${itemData.price}</Text>
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                )
            }}
        />
    )
}

可选优化

  • 当前keyExtractor用数组下标作为key,列表数据更新时容易出现组件复用错乱的问题,可以替换为商品自带的唯一ID作为key,提升渲染稳定性。
  • render阶段每次都会遍历results重新组装finalGames数组,数据量较大时会产生不必要的性能开销,可以把组装后的finalGames存入state,仅在接口数据更新时重新计算,减少重复遍历。

内容的提问来源于stack exchange,提问作者Chanrithisak Phok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.19 09:36:04