首页 文章

firebase问题并做出本机反应,添加数据

提问于
浏览
1

我正在编写使用react native和firebase创建一个todo应用程序,我跟进了一个youtube来开发一个保存到文件而不是firebase的应用程序,但是在应用程序中读取包含firebase但我不知道如何绑定数据到它并确保直到单击提交按钮,然后保存到数据库并将其显示在页面上 .

import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    TextInput,
    ScrollView,
    TouchableOpacity
} from 'react-native';
import Note from './Note';
import firebase from 'firebase';
export default class Main extends Component {
    constructor(props){
        super(props);
        this.state = {
            noteArray: [],
            noteText: '',
        };
    }

    componentWillMount() {

        var config = {
           apiKey: "AIzaSyAB3bO5C7pcLYv745DwwPqUicAshRTdzYk",
           authDomain: "mytodo-6b198.firebaseapp.com",
           databaseURL: "https://mytodo-6b198.firebaseio.com",
           projectId: "mytodo-6b198",
           storageBucket: "",
           messagingSenderId: "314761285731"
         };
         firebase.initializeApp(config);

         //console.log(firebase);

         firebase.database().ref('todo/001').set(
           {  
            note: this.state.noteText,
             name: "Tola"
           }
         ).then(() =>{
           console.log('inserted');
         }).catch((error) =>{
           console.log(error);
         });
        }

    render() {
        let notes = this.state.noteArray.map((val, key)=>{
            return <Note key={key} keyval={key} val={val}
                    deleteMethod={()=>this.deleteNote(key)}/>
        });
        return (
            <View style={styles.container}>
                <View style={styles.header}>
                    <Text style={styles.headerText}>Todo App</Text>
                </View>
                <ScrollView style={styles.scrollContainer}>
                    {notes}
                </ScrollView>
                <View style={styles.footer}>
                    <TextInput 
                        style={styles.textInput}
                        placeholder='>note'
                        onChangeText={(noteText)=> this.setState({noteText})}
                        value={this.state.noteText}
                        placeholderTextColor='white'
                        underlineColorAndroid='transparent'>
                    </TextInput>
                </View>
                <TouchableOpacity onPress={ this.addNote.bind(this) } style={styles.addButton}>
                    <Text style={styles.addButtonText}>+</Text>
                </TouchableOpacity>
            </View>
        );
    }
    addNote(){
        if(this.state.noteText){
            var d = new Date();
            this.state.noteArray.push({
                'date':d.getFullYear()+
                "/"+(d.getMonth()+1) +
                "/"+ d.getDate(),
                'note': this.state.noteText
            });
            this.setState({ noteArray: this.state.noteArray });
            this.setState({noteText:''});
        }
    }
    deleteNote(key){
        this.state.noteArray.splice(key, 1);
        this.setState({noteArray: this.state.noteArray});
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    header: {
        backgroundColor: '#E91E63',
        alignItems: 'center',
        justifyContent:'center',
        borderBottomWidth: 10,
        borderBottomColor: '#ddd'
    },
    headerText: {
        color: 'white',
        fontSize: 18,
        padding: 26
    },
    scrollContainer: {
        flex: 1,
        marginBottom: 100
    },
    footer: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        zIndex: 10
    },
    textInput: {
        alignSelf: 'stretch',
        color: '#fff',
        padding: 20,
        backgroundColor: '#252525',
        borderTopWidth:2,
        borderTopColor: '#ededed',
        marginBottom: 30
    },
    addButton: {
        position: 'absolute',
        zIndex: 11,
        right: 20,
        bottom: 90,
        backgroundColor: '#E91E63',
        width: 70,
        height: 70,
        borderRadius: 35,
        alignItems: 'center',
        justifyContent: 'center',
        elevation: 8
    },
    addButtonText: {
        color: '#fff',
        fontSize: 24
    }
});

还有一个视频教程,可以在本机反应,firebase和上下文API中学习CRUD . 我很乐意看一个 . 谢谢

Note.js

import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    TouchableOpacity,
} from 'react-native';
export default class Note extends Component {
    render() {
        return (
            <View key={this.props.keyval} style={styles.note}>
                <Text style={styles.noteText}>{this.props.val.date}</Text>
                <Text style={styles.noteText}>{this.props.val.note}</Text>
                <TouchableOpacity onPress={this.props.deleteMethod} style={styles.noteDelete}>
                    <Text style={styles.noteDeleteText}>D</Text>
                </TouchableOpacity>
            </View>
        );
    }
}

1 回答

  • 1

    您需要创建用于创建有效负载和保存数据的功能 . 我建议你使用箭头函数和异步任务的承诺 . 试试这个,让我知道它是否对你有帮助 .

    import React, { 
    Component 
    } from 'react';
    
    import {
        View,
        Text,
        StyleSheet,
        TextInput,
        ScrollView,
        TouchableOpacity
    } from 'react-native';
    
    import Note from './Note';
    
    // in the future i would recommend you to use react-native-firebase. 
    //but for learning purposes it's ok.
    
    import firebase from 'firebase';
    
    export default class Main extends Component {
    
        constructor(props){
          super(props);
          this.state = {
            noteArray: [],
            noteText: '',
          };
        }
    
        componentWillMount() {
    
          var config = {
             apiKey: "AIzaSyAB3bO5C7pcLYv745DwwPqUicAshRTdzYk",
             authDomain: "mytodo-6b198.firebaseapp.com",
             databaseURL: "https://mytodo-6b198.firebaseio.com",
             projectId: "mytodo-6b198",
             storageBucket: "",
             messagingSenderId: "314761285731"
           };
           firebase.initializeApp(config);  
           // end of componentWillMount
        }
    
    
        // create ALL needed functions   
    
    
        // ist an arrow function
        createNote = () => {
    
          //create a promise for waiting until element is succesfully created
          return new Promise((resolve, reject) => {
            //extract current states 
            const { noteArray, noteText } = this.state
    
            //create newElement
            var d = new Date();
            const newElement = {
              'date':d.getFullYear()+ "/"+(d.getMonth()+1) + "/"+ d.getDate(),
              'note': noteText
            }
    
            //set all states
            this.setState({
               noteArray: [...noteArray, newElement ], //correct array-state manipulation
               noteText:''                  
            }, () => resolve(newElement)) //new element ist passed as params to next then
    
          })
        }
    
    
        _addNoteToFirebase = () => {
          //this is an arrow function. 
          //myfunc = (params) => { /*custom logic*/}
    
          const refInDatabase = firebase.database().ref('todo/001');
          this.createNote()
            .then((elementRecived) => refInDatabase.update(elementRecived))
            .then(() => console.log('inserted'))
            .catch((error) => console.log(error));
        }
    
        deleteNote = (key) => {
          const { noteArray } = this.state
          this.setState({
            noteArray: noteArray.splice(key, 1) 
          })
        }   
    
        // here is where render method starts
        render() {
            let notes = this.state.noteArray.map((val, key)=>{
              return <Note 
                        key={key} 
                        keyval={key}
                        val={val}
                        deleteMethod={() => deleteNote(key)}
                      />
            });
            return (
                <View style={styles.container}>
                    <View style={styles.header}>
                        <Text style={styles.headerText}>Todo App</Text>
                    </View>
                    <ScrollView style={styles.scrollContainer}>
                        {notes}
                    </ScrollView>
                    <View style={styles.footer}>
                        <TextInput 
                            style={styles.textInput}
                            placeholder='>note'
                            onChangeText={(noteText)=> this.setState({noteText})}
                            value={this.state.noteText}
                            placeholderTextColor='white'
                            underlineColorAndroid='transparent'>
                        </TextInput>
                    </View>
                    <TouchableOpacity onPress={this._addNoteToFirebase} style={styles.addButton}>
                        <Text style={styles.addButtonText}>+</Text>
                    </TouchableOpacity>
                </View>
            );
        } 
    
    }
    const styles = StyleSheet.create({
        container: {
            flex: 1,
        },
        header: {
            backgroundColor: '#E91E63',
            alignItems: 'center',
            justifyContent:'center',
            borderBottomWidth: 10,
            borderBottomColor: '#ddd'
        },
        headerText: {
            color: 'white',
            fontSize: 18,
            padding: 26
        },
        scrollContainer: {
            flex: 1,
            marginBottom: 100
        },
        footer: {
            position: 'absolute',
            bottom: 0,
            left: 0,
            right: 0,
            zIndex: 10
        },
        textInput: {
            alignSelf: 'stretch',
            color: '#fff',
            padding: 20,
            backgroundColor: '#252525',
            borderTopWidth:2,
            borderTopColor: '#ededed',
            marginBottom: 30
        },
        addButton: {
            position: 'absolute',
            zIndex: 11,
            right: 20,
            bottom: 90,
            backgroundColor: '#E91E63',
            width: 70,
            height: 70,
            borderRadius: 35,
            alignItems: 'center',
            justifyContent: 'center',
            elevation: 8
        },
        addButtonText: {
            color: '#fff',
            fontSize: 24
        }
    });
    

相关问题