【问题标题】:issue with firebase and react native, adding datafirebase 问题和本机反应,添加数据
【发布时间】:2019-05-10 07:57:09
【问题描述】:

我正在写使用 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
    }
});

还有一个视频教程来学习原生 react、firebase 和 context 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>
        );
    }
}

【问题讨论】:

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


    【解决方案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
        }
    });
    

    【讨论】:

    • 谢谢,一旦我输入一个新项目并且删除功能不再起作用,它就会覆盖。谢谢
    • 您需要执行其他自定义逻辑。我不确定你的笔记组件是做什么的。但请记住,您不能直接操纵状态。这被认为是一种不好的做法。在 Internet 上搜索 React Native 中的数组状态操作。
    • 让我把它加起来
    • 我已经更正了代码 then((elementRecived) => refInDatabase.push(elementRecived)) 并且项目是按顺序添加的,但问题是,我的列表视图。我知道这是要使用的代码,但“如何”是问题 var starCountRef = firebase.database().ref('path'); starCountRef.on('value', function(snapshot) { updateStarCount(postElement, snapshot.val()); });
    • “如何”是什么意思?你能说清楚吗?
    猜你喜欢
    • 2017-08-05
    • 2020-03-20
    • 2019-03-18
    • 2016-11-10
    • 2019-10-10
    • 1970-01-01
    • 2020-07-20
    • 2018-01-19
    • 1970-01-01
    相关资源
    最近更新 更多