为什么即使添加额外数据后,React-Native中的FlatList也不会更新?

时间:2020-06-01 20:35:10

标签: javascript typescript react-native mobile react-native-flatlist

在过去的几个小时中,我试图列出一个简单的列表,您可以通过在文本字段中键入内容并按按钮来扩展列表。但是,即使更改了额外数据的内容,它也不会更新我的FlatList。我究竟做错了什么? 请不要介意updateTask上的硬编码ID,它仅用于调试。

import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet, FlatList } from 'react-native'

const DATA = [
  {
    id: '1',
    title: 'First Item',
  },
  {
    id: '2',
    title: 'Second Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
];

function Item({ title }) {
  return (
    <View style={styles.item}>
      <Text style={styles.title}>{title}</Text>
    </View>
  );
}

class Inputs extends Component {
   state = {
      task: '',
   }
   handleTask = (text) => {
      this.setState({ task: text })
   }
   updateTask = (task) => {
      DATA.push({
        id: '4',
        title: task
      })
      alert(DATA.length + task);
   }
   render() {
      return (
         <View style = {styles.container}>

          <FlatList
             data={DATA}
             renderItem={({ item }) => <Item title={item.title} />}
             keyExtractor={item => item.id}
             extraData={DATA.length}
          />

            <TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Task"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handleTask}/>


            <TouchableOpacity
               style = {styles.submitButton}
               onPress = {
                  () => this.updateTask(this.state.task)
               }>
               <Text style = {styles.submitButtonText}> Submit </Text>
            </TouchableOpacity>
         </View>
      )
   }
}
export default Inputs

const styles = StyleSheet.create({
   container: {
      paddingTop: 23
   },
   input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 40,
   },
   submitButtonText:{
      color: 'white'
   },
   item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
})

1 个答案:

答案 0 :(得分:0)

更改

extraData={DATA.length}

extraData={this.state}

希望有帮助。