简体   繁体   English

为什么我在 React-Native 中的 FlatList 没有更新,即使添加了额外数据?

[英]Why my FlatList in React-Native doesn't update, even after adding extradata?

For the last couple of hours I am trying to make simple list, that you can expand by typing something into text field and pressing button.在过去的几个小时里,我正在尝试制作简单的列表,您可以通过在文本字段中输入一些内容并按下按钮来扩展它。 But it doesn't update my FlatList, even after changing content of extra data.但即使更改了额外数据的内容,它也不会更新我的 FlatList。 What am I doing wrong?我究竟做错了什么? Please don't mind hard coded ID on updateTask, it is only for debugging.请不要介意 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,
  },
})

change改变

extraData={DATA.length}

to

extraData={this.state}

Hope it help.希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM