ReactNative中FlatList组件不渲染,参照官方代码修改后仍无法显示如何解决
FlatList不渲染问题排查与修复
核心问题
- 你在类组件中错误使用了函数组件专属的
useStateHook,这是导致功能异常的根本原因。Hook只能在React函数组件或自定义Hook中调用,不能在class类组件中直接使用,你将useState的返回值直接赋值给类属性,状态更新不会触发组件重渲染,FlatList自然不会响应状态变化,甚至初始渲染都会异常。 - 外层
styles.page添加了justifyContent: center和alignItems: center属性,内部SafeAreaView写死了宽高750,在绝大多数手机屏幕上都会超出视口,你大概率只能看到番茄色背景块的一角,看不到列表内容。 - 状态没有存放在类组件的
state中,extraData绑定的普通类属性变化不会触发FlatList重渲染。
修复后可运行代码
import * as React from "react"; import { Component } from "react"; import { StyleSheet, Text, View, TouchableOpacity, FlatList, SafeAreaView } from "react-native"; import { Driver } from "../models/Driver"; const styles = StyleSheet.create({ page: { flex: 1, backgroundColor: "#FFF" }, container: { flex: 1, backgroundColor: "tomato" }, item: { padding: 10, fontSize: 18, height: 44, }, title: { fontSize: 18 } }); const DATA = [ { id: "bd7acbea-c1b1-46c2-aed5-3ad53abb28ba", title: "First Item", }, { id: "3ac68afc-c605-48d3-a4f8-fbd91aa97f63", title: "Second Item", }, { id: "58694a0f-3da1-471f-bd96-145571e29d72", title: "Third Item", }, ]; const Item = ({ item, onPress, backgroundColor, textColor }: { item: any; onPress: any; backgroundColor: any; textColor: any; }) => ( <TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}> <Text style={[styles.title, textColor]}>{item.title}</Text> </TouchableOpacity> ); export default class TabFourScreen extends Component { drivers: Driver[] = []; state = { selectedId: null } renderItem = ({ item }: {item: any}) => { const backgroundColor = item.id === this.state.selectedId ? "#6e3b6e" : "#f9c2ff"; const color = item.id === this.state.selectedId ? "white" : "black"; return ( <Item item={item} onPress={() => this.setState({selectedId: item.id})} backgroundColor={{ backgroundColor }} textColor={{ color }} /> ); } render = () => { return ( <View style={styles.page}> <SafeAreaView style={styles.container}> <FlatList data={DATA} renderItem={this.renderItem} keyExtractor={(item) => item.id} extraData={this.state.selectedId} /> </SafeAreaView> </View> ); } }
FlatList正常渲染必要条件
- 必须给FlatList的所有上级容器设置明确的可占用空间(比如
flex:1),不能无宽高约束,否则FlatList会默认占0高度无法渲染 data属性必须是稳定的数组引用,不要每次渲染都生成新数组导致不必要的重渲染renderItem必须返回合法的React节点,不能返回undefined- 如果需要FlatList响应渲染项之外的状态变化,必须把对应的状态传给
extraData属性
内容的提问来源于stack exchange,提问作者ajavad
相关产品推荐
相关产品推荐

