You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native:调用shuffle函数后FlatList无法更新如何解决

问题核心原因

你的代码有3个核心问题导致FlatList没有更新:

  • 你声明的Games是普通局部变量,不属于React的state或props,修改它不会触发组件重渲染,FlatList自然不会刷新
  • 你写的Shuffle函数是原地修改原数组,没有生成新的数组引用,哪怕Games是state,React的浅比较也检测不到变化,不会触发重渲染
  • FlatList没有配置extraData属性,无法感知除基础data外的状态变化触发刷新

修改后完整代码

需要先引入React的useState钩子,调整后代码如下:

import React, { useState } from 'react';
import { View, Image, Text, FlatList, Button } from 'react-native';

const Display = (props) => {
  return (
    <View>
      <View style={{ flexDirection: 'row' }}>
        <Image source={props.img} style={{ width: 200, height: 200 }} />
        <Text>{props.title}</Text>
      </View>
    </View>
  );
}

function Other({ navigation }) {
  // 将列表数据声明为React state,修改时才会触发组件重渲染
  const [games, setGames] = useState([
    { title: "Tic Tac Toe", img: require("./pics/tictac.png") },
    { title: "Connect Four", img: require("./pics/ConnectFour.jpg") },
    { title: "Monopoly", img: require("./pics/mono.png") },
  ]);

  function Shuffle(array){
    // 先拷贝原数组,避免原地修改,生成新的数组引用让React能检测到变化
    const newArray = [...array];
    let x, y, z;
    // 调整循环逻辑适配任意长度的数组,不需要写死长度
    for(x = 0; x < newArray.length; x++){
      y = Math.floor(Math.random() * newArray.length)
      z = newArray[x];
      newArray[x] = newArray[y]
      newArray[y] = z
    }
    return newArray;
  }

  return (
    <View>
      <FlatList 
        data={games} 
        renderItem={({ item }) => <Display title={item.title} img={item.img} />}
        // 配置extraData,state变化时主动触发FlatList刷新
        extraData={games}
        // 新增keyExtractor避免FlatList抛出缺少唯一key的警告
        keyExtractor={(item, index) => index.toString()}
      />
      <Button title="Shuffle" onPress={() => {
        // 生成打乱后的新数组,更新state触发重渲染
        const shuffledGames = Shuffle(games);
        setGames(shuffledGames);
      }} />
    </View>
  ); 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:57:00