проблема с firebase и реагирование на натив, добавление данных - PullRequest
0 голосов
/ 09 декабря 2018

Я пишу, чтобы создать приложение todo, использующее реагирующий нативный и firebase, я разработал 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
    }
});

И есть видеоурок для изучения CRUD в нативном реагировании, Firebase и контекстном API.Я буду рад посмотреть один.Спасибо

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 Ответ

0 голосов
/ 09 декабря 2018

Вам необходимо создать функцию для создания полезной нагрузки и сохранения данных.Я рекомендую вам использовать функции стрелок и обещание для асинхронной задачи.Попробуйте и дайте мне знать, помогло ли это вам.

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
    }
});
...