You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React Native中FlatList无法动态更新的问题求助

Fixing Dynamic FlatList Updates in React Native

Hey there! I see you're having trouble getting your FlatList to update with new items added via a timer—let's fix that right away.

The Root Cause

The issue is how you're updating your state array. When you do let tempArray = this.state.dataToRender; tempArray.push(temp);, you're mutating the original state array directly instead of creating a new array. React uses shallow comparison to detect state changes, so since the array reference hasn't changed, it doesn't trigger a re-render for the FlatList.

The Fix for Class Component

Update your componentDidMount method to create a new array instead of mutating the existing one. You can use the spread operator (...) to copy the old array and add the new item:

componentDidMount() {
  let counter = 0;
  const interval = setInterval(() => {
    try {
      const temp = { 
        "id": ++counter + "", 
        "name": "name" + counter, 
        "des": "des" + counter 
      };
      
      // Create a new array with existing items + new item
      this.setState(prevState => ({
        dataToRender: [...prevState.dataToRender, temp]
      }), () => {
        // Use setState callback to log updated state (since setState is async)
        console.log(this.state.dataToRender);
      });
      
      if(counter === 10) {
        clearInterval(interval);
      }
    } catch (e) {
      console.log(e.message);
    }
  }, 2000);
}

Key Notes:

  • Using prevState in setState is safer when your new state depends on the previous state—it avoids race conditions.
  • setState is asynchronous, so if you want to log the updated state, use the callback function instead of logging right after setState.

Alternative: Function Component with Hooks

Since React Native now recommends function components with Hooks, here's a cleaner implementation:

import React, { useState, useEffect } from "react";
import { View, FlatList } from "react-native";
import { ListItem, List } from "react-native-elements";

export default function JoinSession() {
  const [dataToRender, setDataToRender] = useState([{ 
    "id": "0", 
    "name": "name0", 
    "des": "des0" 
  }]);

  useEffect(() => {
    let counter = 0;
    const interval = setInterval(() => {
      const temp = { 
        "id": ++counter + "", 
        "name": "name" + counter, 
        "des": "des" + counter 
      };
      
      // Update state with a new array
      setDataToRender(prevData => [...prevData, temp]);
      
      if(counter === 10) {
        clearInterval(interval);
      }
    }, 2000);

    // Cleanup timer when component unmounts to prevent memory leaks
    return () => clearInterval(interval);
  }, []);

  const renderList = (item) => (
    <ListItem roundAvatar title={item.name} subtitle={item.des} />
  );

  return (
    <View style={{ flex: 1, alignItems: "stretch", backgroundColor: "skyblue" }}>
      <List>
        <FlatList 
          data={dataToRender} 
          renderItem={({ item }) => renderList(item)} 
          keyExtractor={item => item.id} 
        />
      </List>
    </View>
  );
}

This version uses:

  • useState to manage the list state
  • useEffect to handle the timer and cleanup (prevents memory leaks when the component unmounts)
  • Function state updates to safely depend on the previous state

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

火山引擎 最新活动