#reactjs #react-native #sqlite #expo
#reactjs #react-native #sqlite #выставка
Вопрос:
Я пытаюсь создать систему торговых точек, которая использует базу данных Sqlite на телефоне, используя пакет expo-sqlite, когда я делаю это с помощью const db = SQLite.openDatabase(‘dbName’), она работает просто отлично, но когда я пытаюсь импортировать внешнюю базу данных, она выдает эту ошибку: 1:Ошибка: Не удается разрешить модуль ./debugger-ui/debuggerWorker.aca173c4
из `: 2: ошибка ссылки: компонент не определен и не удается разрешить модуль ВОТ РЕПОЗИТОРИЙ GITHUB https://github.com/16isaac89/point-of-sale
это код, из которого я импортирую и использую его
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
StatusBar,
ImageBackground,
Image,
TextInput,
Dimensions,
TouchableOpacity,
} from 'react-native';
import bgImage from '../assets/images/bgImage.jpg'
import logoLogin from '../assets/images/logos.png'
import Icon from 'react-native-vector-icons/Ionicons'
import Icons from 'react-native-vector-icons/FontAwesome'
import * as actions from '../Redux/Actions';
import { connect } from "react-redux";
import * as FileSystem from 'expo-file-system';
import {Asset} from "expo-asset";
const { width: WIDTH } = Dimensions.get('window')
import * as SQLite from 'expo-sqlite'
class Login extends Component {
getCurrentDate=()=>{
var date = new Date(); /* creating object of Date class */
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
var midday = "AM";
midday = (hour >= 12) ? "PM" : "AM"; /* assigning AM/PM */
hour = (hour == 0) ? 12 : ((hour > 12) ? (hour - 12): hour); /* assigning hour in 12-hour format */
hour = this.updateTime(hour);
min = this.updateTime(min);
sec = this.updateTime(sec);
return hour " : " min " : " sec " " midday; /* adding time to the div */
var t = setTimeout(currentTime, 1000)
}
updateTime=(k)=> { /* appending 0 before time elements if less than 10 */
if (k < 10) {
return "0" k
}
else {
return k;
}
}
openDatabaseIShipWithApp =async()=> {
const internalDbName = "syntaxpos.db"; // Call whatever you want
const sqlDir = FileSystem.documentDirectory "SQLite/";
if (!(await FileSystem.getInfoAsync(sqlDir internalDbName)).exists) {
await FileSystem.makeDirectoryAsync(sqlDir, {intermediates: true});
const asset = Asset.fromModule(require("./assets/db/"));
await FileSystem.downloadAsync(asset.uri, sqlDir internalDbName);
}
return SQLite.openDatabase(internalDbName);
}
async componentDidMount(){
// this.openDatabaseIShipWithApp()
console.log(this.props.dataUser)
if(this.props.loggedin === true){
this.props.navigation.navigate('Home');
}
}
onAuthComplete=(props)=>{
if(this.props.loggedin = true){
this.props.navigation.navigate('Main');
}
}
loginPin = () =>{
let username = this.props.username
let password = this.props.lpin;
//console.log(username, password)
this.props.getUser({username,password})
}
onPinChange(text){
this.props.pinChanged(text);
}
onusernameChange(text){
this.props.usernameChanged(text);
}
render(){
return (
<ImageBackground source={bgImage} style={styles.backgroundContainer}>
<View style={styles.logoContainer}>
<Image source={logoLogin} style={styles.logoLogin} />
<Text style={styles.logoText}>Business Management Made Easier</Text>
<Text style={styles.textLogin}>LOGIN</Text>
</View>
<View>
<Icons name={'user'} size={28} color={'black'}
style={styles.inputIcon}/>
<TextInput
onChangeText={this.onusernameChange.bind(this)}
value = {this.props.username}
style={styles.inputUsername}
placeholder={'USER NAME'}
placeholderTextColor={'black'}
underlineColorAndroid='transparent'
/>
</View>
<View>
<Icon name={'ios-lock'} size={28} color={'black'}
style={styles.inputIcon}/>
<TextInput
onChangeText={this.onPinChange.bind(this)}
value = {this.props.lpin}
style={styles.inputUsername}
placeholder={'PIN'}
placeholderTextColor={'black'}
underlineColorAndroid='transparent'
keyboardType = 'numeric'
/>
</View>
<TouchableOpacity activeOpacity={.7} style={styles.btnLogin} onPress={()=> this.loginPin()}>
<Text style={styles.textsubmit} > LOGIN </Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity={.7} style={styles.btnLogin} onPress={()=> this.openDatabaseIShipWithApp()}>
<Text style={styles.textsubmit} > LOGIN </Text>
</TouchableOpacity>
</ImageBackground>
);}
};
const styles = StyleSheet.create({
backgroundContainer:{
flex: 1,
width: null,
height: null,
justifyContent: 'center',
alignItems: 'center',
},
logoLogin:{
width: 60,
height: 80,
borderRadius:10
},
logoContainer:{
alignItems:'center',
marginBottom: 50
},
logoText:{
color: 'white',
fontSize: 15,
fontWeight: '500',
marginTop: 10,
opacity: 0.8
},
inputUsername:{
width: WIDTH - 75,
height: 45,
borderRadius: 45,
fontSize: 16,
fontWeight: 'bold',
backgroundColor: '#e3e3e3',
color: 'black',
paddingLeft: 48,
marginTop: 15,
marginHorizontal: 25,
opacity: 0.5
},
inputIcon:{
position: 'absolute',
top: 21,
left: 43
},
btnEye:{
position: 'absolute',
top: 24,
right: 43
},
btnLogin:{
width: WIDTH - 75,
height: 45,
borderRadius: 45,
backgroundColor: '#2bb358',
justifyContent: 'center',
marginTop: 30,
},
textsubmit: {
color: 'white',
fontSize: 18,
textAlign: 'center',
fontWeight: 'bold'
},
textLogin:{
color: 'white',
fontSize: 26,
fontWeight: 'bold',
marginTop: 30,
}
});
const mapStateToProps = (state) =>{
return{
dataUser: state.auth.dataUser,
lpin: state.auth.pin,
username:state.auth.username,
loggedin: state.auth.loggedin
}
}
export default connect(mapStateToProps, actions)(Login);
this is the metro config
const { getDefaultConfig } = require('@expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
module.exports = {
resolver: {
assetExts: [...defaultConfig.resolver.assetExts, 'db'],
},
};
this is the package.json
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject"
},
"dependencies": {
"@expo/metro-config": "^0.1.43",
"@react-native-community/async-storage": "^1.6.2",
"@react-native-community/datetimepicker": "3.0.0",
"@react-native-picker/picker": "^1.9.3",
"axios": "^0.19.0",
"expo": "~39.0.2",
"expo-asset": "~8.2.0",
"expo-file-system": "~9.2.0",
"expo-image-picker": "~9.1.1",
"expo-sharing": "~8.4.1",
"expo-sqlite": "~8.4.0",
"expo-status-bar": "~1.0.2",
"moment": "^2.29.1",
"native-base": "^2.13.8",
"patch-package": "^6.2.2",
"react": "16.13.1",
"react-csv": "^2.0.3",
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-39.0.4.tar.gz",
"react-native-awesome-alerts": "^1.4.2",
"react-native-elements": "^1.2.7",
"react-native-gesture-handler": "^1.5.0",
"react-native-modal-datetime-picker": "^9.1.0",
"react-native-numeric-input": "^1.8.3",
"react-native-reanimated": "^1.4.0",
"react-native-screens": "^1.0.0-alpha.23",
"react-native-searchable-list": "^1.1.3",
"react-native-simple-toast": "^1.1.3",
"react-native-splash-screen": "^3.2.0",
"react-native-touchable-scale": "^2.1.0",
"react-native-vector-icons": "^6.6.0",
"react-native-web": "~0.13.12",
"react-navigation": "^4.0.10",
"react-navigation-drawer": "^2.3.3",
"react-navigation-stack": "^1.10.3",
"react-navigation-tabs": "^2.5.6",
"react-redux": "^7.1.3",
"redux": "^4.0.4",
"redux-logger": "^3.0.6",
"redux-promise-middleware": "^6.1.2",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"@babel/core": "~7.9.0"
},
"private": true
}
Ответ №1:
Используйте этот код для открытия базы данных
async function openDb() {
if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory
'SQLite')).exists) {
await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory
'SQLite');
}
await FileSystem.downloadAsync(
Asset.fromModule(require('./assets/db/user.db')).uri,
FileSystem.documentDirectory 'SQLite/user.db'
);
return SQLite.openDatabase('user.db');
}
const db = openDb();
Затем создайте файл metro.config.js в корневом каталоге вашего приложения и добавьте в него этот код
const { getDefaultConfig } = require('expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
module.exports = {
resolver: {
assetExts: [...defaultConfig.resolver.assetExts, 'db'],
},
};
Этот код в metro.config.js позволяет вашему приложению распознавать любые расширения файлов .db
Затем, наконец, остановите и перезапустите свое приложение, приветствия