Я учусь использовать реагировать нативно для приложения Android.Я установил в свою папку проект PouchDB, а также у меня есть CouchDB.
Я пытаюсь понять, как работает соединение с БД, используя простые формы входа и регистрации.
Например, япришлось создать страницу js с именем DB.js примерно так:
import PouchDB from 'pouchdb-react-native';
PouchDB.plugin(require('pouchdb-find'));
PouchDB.plugin(require('pouchdb-adapter-asyncstorage').default);
PouchDB.plugin(require('pouchdb-authentication'));
class DB {
constructor(dbName, username, password, protocol, host, port){
this.remoteDB = null;
this.localDB = new PouchDB(dbName);
this.replication(
'dbName' = ‘myDBName’,
'username' = ‘myUsername’,
'password' = ‘myPassword’,
'protocol' = 'https',
'host' = ‘myHost’,
'port' = myPortNumber
);}
localdb(){
return this.localDB;
}
syncDB(){
this.localdb().sync(this.remoteDB, {
live: true,
retry: true,
attachments:true,
}).on('change', function (change) {
//
}).on('paused', function (paused) {
// console.log('paused:' + paused)
}).on('active', function (active) {
// console.log('active:' + active)
}).on('error', function (error) {
// console.log('error:' + error)
});
}
replication(dbName, username, password, protocol, host, port){
this.createDB(dbName, username, password, protocol, host, port);
this.loginDB(username, password);
}
В конструкторе я инициализировал базу данных, а затем синхронизировал ее.
Теперь, например,, Я должен создать форму для регистрации.
Register.js
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Button,
TouchableHighlight,
Image,
Alert
} from 'react-native';
import { Actions } from 'react-native-router-flux';
export default class SignUpView extends Component {
constructor(props) {
super(props);
state = {
fullName: '',
email : '',
password: '',
}
}
//
SignInUser(User){
this.user = {
_id:id,
fullName: fullName,
email: email,
password: password
}
return new Promise((resolve, reject) => {
user.localdb().post(this.user)
.then((response) => {this.user._rev = response.rev; resolve(response)})
.catch((error) => {reject(error)})
})
}
//
render() {
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/male-user/ultraviolet/50/3498db'}}/>
<TextInput style={styles.inputs}
placeholder="Full name"
keyboardType="email-address"
underlineColorAndroid='transparent'
onChangeText={(fullName) => this.setState({fullName})}/>
</View>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/message/ultraviolet/50/3498db'}}/>
<TextInput style={styles.inputs}
placeholder="Email"
keyboardType="email-address"
underlineColorAndroid='transparent'
onChangeText={(email) => this.setState({email})}/>
</View>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/key-2/ultraviolet/50/3498db'}}/>
<TextInput style={styles.inputs}
placeholder="Password"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(password) => this.setState({password})}/>
</View>
<TouchableHighlight style={[styles.buttonContainer, styles.signupButton]}
onPress={ () => SignInUser(this.state) }>
<Text style={styles.signUpText}>Sign up</Text>
</TouchableHighlight>
<TouchableHighlight style={[styles.buttonContainer, styles.signupButton]} onPress={() => Actions.scarlet()}>
<Text style={styles.signUpText}>GoTo Scarlet</Text>
</TouchableHighlight>
</View>
);
}
}
И, наконец, файл js для размещения в базе данных информации
SignInUser.js
export default class SignInUser {
SignInUser(User){
this.user = {
_id:id,
fullName: fullName,
email: email,
password: password
}
return new Promise((resolve, reject) => {
user.localdb().post(this.user)
.then((response) => {this.user._rev = response.rev; resolve(response)})
.catch((error) => {reject(error)})
})
}
}
При запуске эмулятора появляется ошибка в функции:
onPress={() => this.onClickListener('SignInUser')}>
Я не знаю, произошла ли ошибка из-за функции или кода, который был плохо структурирован.Раз я пытаюсь понять как можно больше, не могли бы вы мне помочь?большое спасибо