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
相关产品推荐
相关产品推荐

