【问题标题】:Why my FlatList in React-Native doesn't update, even after adding extradata?为什么我在 React-Native 中的 FlatList 没有更新,即使添加了额外数据?
【发布时间】:2020-09-20 05:58:18
【问题描述】:

在过去的几个小时里,我正在尝试制作简单的列表,您可以通过在文本字段中输入一些内容并按下按钮来扩展它。但即使更改了额外数据的内容,它也不会更新我的 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,
  },
})

【问题讨论】:

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


    【解决方案1】:

    改变

    extraData={DATA.length}
    

    extraData={this.state}
    

    希望对您有所帮助。

    【讨论】:

    • 它变得更好了,现在有时会更新,但我无法确定何时更新。感觉是随机更新的
    • 将您的数组置于状态,每当状态发生变化时,它都会重新渲染。(抱歉,EN 不好)
    猜你喜欢
    • 2018-11-10
    • 2021-07-22
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2019-10-18
    • 2019-10-04
    相关资源
    最近更新 更多