gpt4 book ai didi

javascript - 问题与 firebase 和 native react ,添加数据

转载 作者:行者123 更新时间:2023-11-29 23:12:12 24 4
gpt4 key购买 nike

我写信是为了使用 react native 和 firebase 创建一个待办事项应用程序,我跟进了一个 youtube 来开发一个保存到文件而不是 firebase 的应用程序,但是阅读以在应用程序中包含 firebase 但我不知道如何将数据绑定(bind)到它并确保直到单击提交按钮,然后它才会保存到数据库并显示在页面上。

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。我很乐意看一个。谢谢

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

最佳答案

您需要创建用于创建有效载荷和保存数据的函数。我建议您使用箭头函数和异步任务的 promise 。试试这个,让我知道它是否对您有帮助。

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

关于javascript - 问题与 firebase 和 native react ,添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53688357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com