FlatList 不在功能组件中重新渲染?

当我按下 Flatlist 数据中的任何项目时,我正在实现一些清单组件,我向对象添加了一个切换属性并制作它true并基于它我呈现了一个检查绿色图标,


但在这种情况下,Flatlist,而不是重新渲染,我为 Flatlist 添加了 extraData 道具并将数据传递给它,但效果不佳!


这是代码


import React, {useState} from 'react';

import {StyleSheet, Text, View, FlatList, TouchableOpacity} from 'react-native';

import Feather from 'react-native-vector-icons/Feather';

import {Theme} from '../utils/colors';


const Data = [

  {

    id: 1,

    first_name: 'Sile',

  },

  {

    id: 2,

    first_name: 'Clementia',

  },

  {

    id: 3,

    first_name: 'Brita',

  },

  {

    id: 4,

    first_name: 'Duke',

  },

  {

    id: 5,

    first_name: 'Hedvig',

  }

];


const BottomModal = () => {

  const [countries, setCountries] = useState(Data);


  const itemSelected = (id) => {

    console.log('current id: ', id);

    let datamanipulat = countries;

    datamanipulat.map((item) => {

      item.toggle = false;

      if (item.id === id) {

        item.toggle = true;

      }

    });

    setCountries(datamanipulat);

    console.log('data after manipulate: ', countries);

  };

  return (

    <View style={styles.container}>

      <FlatList

        ListHeaderComponent={() => (

          <View style={styles.header}>

            <View style={styles.panelHandle} />

          </View>

        )}

        showsVerticalScrollIndicator={false}

        data={countries}

        extraData={countries}

        keyExtractor={(item) => String(item.id)}

        renderItem={({item, index}) => (

          <TouchableOpacity

            key={item.id}

            onPress={() => itemSelected(item.id)}

            style={styles.item}>

            <Text>{`country: ${item.first_name}`}</Text>

            {item.toggle ? (

              <Feather name="check" size={25} color={Theme.PrimaryColor} />

            ) : (

              <Feather name="octagon" size={25} color={Theme.PrimaryColor} />

            )}

          </TouchableOpacity>

        )}

        contentContainerStyle={styles.contentContainerStyle}

      />


森林海
浏览 162回答 1
1回答

海绵宝宝撒

发生这种情况是因为您使用的是相同的数组。如果您像下面这样更改代码,这将正常工作。&nbsp; const itemSelected = (id) => {&nbsp; &nbsp; console.log('current id: ', id);&nbsp; &nbsp; const updated = countries.map((item) => {&nbsp; &nbsp; &nbsp; item.toggle = false;&nbsp; &nbsp; &nbsp; if (item.id === id) {&nbsp; &nbsp; &nbsp; &nbsp; item.toggle = true;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return item;&nbsp; &nbsp; });&nbsp; &nbsp; setCountries(updated);&nbsp; &nbsp; console.log('data after manipulate ++: ', updated);&nbsp; };
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript