【问题标题】:render data in FlatList React Native (expo cli) from firebase realtime database?从firebase实时数据库渲染FlatList React Native(expo cli)中的数据?
【发布时间】:2020-12-06 00:14:26
【问题描述】:

我正在开发一个连接到 Firebase 实时数据库的 ToDo 应用。一切正常。我也可以将数据存储在 Firebase 数据库中,但问题是我无法从数据库中获取任何数据。我想在 ScrollView 中渲染数据,这样当我打开我的应用时,数据可以在 ScrollView 中显示。

我收到错误:ReferenceError: noteArray is not defined

我已经上传了我的整个代码 [codesandbox.io/s/stupefied-snowflake-1lddp?file=/src/App.js][1]

Main.js

             import React, { Component } from "react";
    import {
      StyleSheet,
      Text,
      View,
      TextInput,
      TouchableOpacity,
      FlatList
    } from "react-native";
    import Note from "./note";
    import firebase from "./firebase";
    
    export default class Main extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          noteArray: [],
          noteText: ""
        };
      }
    
      componentDidMount() {
        this.listenForNotes();
      }
    
      listenForNotes() {
        firebase
          .database()
          .ref(`todos`)
          .on("value", function (snapshot) {
            const notes = [];
            snapshot.forEach((child) => {
              notes.push({
                note: child.val().name,
                date: child.val().date,
                key: child.key
              });
            });
            this.setState({
              noteArray: notes
            });
          });
      }
    
      adTask() {
        if (this.state.noteText) {
          var date = new Date();
          var database = firebase.database().ref("todos");
          var key = database.push().key;
          var todo = {
            date:
              date.getDay() +
              "/" +
              (date.getMonth() + 1) +
              "/" +
              date.getFullYear(),
            note: this.state.noteText,
            key: key
          };
          database.child(key).set(todo);
          this.setState({ noteText: "" });
        }
      }
    
      deleteNote(key) {
        // your delete note function
      }
    
      render() {
        return (
          <View style={styles.container}>
            <View style={styles.header}>
              <Text style={styles.headerText}>Todo</Text>
            </View>
            <FlatList
              data={this.state.noteArray}
              renderItem={({ item, index }) => {
                return (
                  <Note
                    key={item.key}
                    note={item.note}
                    date={item.date}
                    deleteMethod={() => this.deleteNote(item.key)}
                    />
                );
              }}
              key={(item) => `${item.key}`}
            />
            <View style={styles.footer}>
              <TextInput
                style={styles.textInput}
                onChangeText={(noteText) => this.setState({ noteText })}
                value={this.state.noteText}
                placeholder="Enter Task"
                placeholderTextColor="white"
                underlineColorAndroid="transparent"
              ></TextInput>
            </View>
            <TouchableOpacity
              onPress={this.adTask.bind(this)}
              style={styles.addButton}
            >
              <Text style={styles.addButtonText}>Add</Text>
            </TouchableOpacity>
          </View>
        );
      }
    }
    
    
        
        

note.js

            import React from "react";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";

export default class Note extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { note, date, key, deleteMethod } = this.props;
    return (
      <View key={key} style={styles.note}>
        <Text style={styles.noteText}>{note}</Text>
        <Text style={styles.noteDate}>{date}</Text>
        <TouchableOpacity onPress={deleteMethod} style={styles.noteDelete}>
          <Text style={styles.noteDeleteText}>
            <AntDesign name="delete" size={24} color="black" />
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  note: {
    position: "relative",
    padding: 20,
    paddingRight: 100,
    borderBottomWidth: 2,
    borderBottomColor: "#ededed"
  },
  noteText: {
    fontWeight: "bold",
    fontSize: 18,
    paddingLeft: 20,
    borderLeftWidth: 10,
    borderLeftColor: "#e91e63"
  },
  noteDate: {
    paddingLeft: 20,
    borderLeftWidth: 10,
    borderLeftColor: "#e91e63"
  },
  noteDelete: {
    position: "absolute",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#2980b9",
    padding: 10,
    top: 10,
    bottom: 10,
    right: 10
  },
  noteDeleteText: {
    color: "white"
  }
});

    
    
      [1]: http://codesandbox.io/s/stupefied-snowflake-1lddp?file=/src/App.js

【问题讨论】:

    标签: javascript reactjs react-native firebase-realtime-database expo


    【解决方案1】:

    它应该是this.state.noteArray,因为 noteArray 是一个状态变量。

    代码沙箱中有几个错误

        <FlatList
          data={noteArray}
          renderItem={({ item, index }) => {
    

    应该是

      <FlatList
          data={this.state.noteArray}
          renderItem={({ item, index }) => {
    

    和key,应该是item.key:

                deleteMethod={() => this.deleteNote(key)}
    

    应该是

                deleteMethod={() => this.deleteNote(item.key)}
    

    this.setState 不存在是因为您有一个函数而不是数组函数。将其更改为以下应该可以工作:

      .on("value",  snapshot => {
        const notes = [];
        snapshot.forEach((child) => {
          notes.push({
            note: child.val().name,
            date: child.val().date,
            key: child.key
          });
        });
        this.setState({noteArray: notes});
      });
    

    【讨论】:

    • 我检查了你的代码,但现在它给出了这个错误 TypeError: Cannot read property 'setState' of null。 this.setState({ noteArray: notes });
    • 我上面的更改不涉及更改 setState。你在看什么?
    • 这就是问题所在。我不明白这个错误
    • 将 noteArray 更改为 this.state.noteArray 后出现此错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2021-03-28
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多