创建 JSON 文件反应原生并加载到数据库中 [英] Create JSON file react native and load in the DB

查看:33
本文介绍了创建 JSON 文件反应原生并加载到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题.我使用 react native 创建了一个应用程序,该应用程序使用蓝牙与外部设备进行通信.当应用程序与两个外部设备连接时,我会从中恢复数据流.我的问题是我应该创建一个 json 文件并加载到数据库中.我该怎么办??

I have a question. I create an app using react native that comunicate with external devices using bluetooth. When the app is connected with the two external devices, I recover a flow of data from these. My problem is that I should create a json file and load in a DB. How can I do??

我恢复了这种数据:

<View>
    <Text>Device Left: </Text>
    <Text>{"Time:" + this.state.time}</Text>
    <Text>{"Acc:" + this.state.acc.join(" ")}</Text>
    <Text>{"Gyr:" + this.state.gyr.join(" ")}</Text>
    <Text>{"Mg:" + this.state.mg.join(" ")}</Text>
    <Text>{"Pressure:" + pressure}</Text>
    <Text> ---- </Text>
    <Text>{"Message:" + this.state.info}</Text>
    <Text>-----------</Text>
</View>
<View>
    <Text>Device Right: </Text>
    <Text>{"Time:" + this.state.time}</Text>
    <Text>{"Acc:" + this.state.acc_dx.join(" ")}</Text>
    <Text>{"Gyr:" + this.state.gyr_dx.join(" ")}</Text>
    <Text>{"Mg:" + this.state.mg_dx.join(" ")}</Text>
    <Text>{"Pressure:" + pressure}</Text>
    <Text> ---- </Text>
    <Text>{"Message:" + this.state.info}</Text>
    <Text>-----------</Text>
</View>

所以我有来自这两个设备的连续数据流.当我单击停止按钮时,我应该将数据加载到 db 中.

So I have a flow continuous of data from these two devices. When I click on a Stop Button I should load the data in db.

推荐答案

如果您不需要查询数据,那么您可以简单地使用 AsyncStorage.

If you don't need to query your data, then you could simply use AsyncStorage.

https://github.com/react-native-community/async-storage

查看下面的代码.

第一个片段

这是一个基本模块,导出2个方法,1个保存数据,另一个加载数据.使用此模块保存的数据将被持久化,即写入磁盘.

This is a basic module, which exports 2 methods, 1 to save data, another to load data. Data saved using this module is persisted, i.e. written to disk.

注意保存的所有数据都是通过JSON.stringify传递的,然后在返回的路上解析.这有助于保存非原始类型,例如对象.

Note that all data saved is passed through JSON.stringify, and then parsed on the way back out. This facilitates saving non-primitive types, such as objects.

import AsyncStorage from '@react-native-community/async-storage';

/*
* @function saveDeviceData This will write the data to disk, with a given key, this * could be written to a SQLite DB file, a flat file, AsyncStorage is an abstract 
* wrapper around this. 
* @param key {String} Key identifier
* @param data {any} Data to save for the given key
*/
export const saveDeviceData = async (key, data) => {
    try {

        await AsyncStorage.setItem(key, JSON.stringify(data));
    } catch (e) {
      console.log(`Error saving data for key ${key}`, data);
      throw e;
    }
};


/*
* @param key {String} Key identifier for data to load
*/
export const loadDeviceData = async (key) => {
    try {

        return JSON.parse(await AsyncStorage.getItem(key);
    } catch (e) {
      console.log(`Error loading data for key ${key}`);
      throw e;
    }
};

第二个片段

这是一个组件的基本示例,它有两种方法,一种用于加载数据,另一种用于保存数据.该组件呈现 2 个按钮,这些按钮绑定到这 2 个方法.

This is a basic example of a component, it has 2 methods, 1 to load data, another to save data. The component renders 2 buttons, these buttons are bound to those 2 methods.

import React, {Component} from "react";
import {saveDeviceData, loadDeviceData} from "./the-module-example-above";

class App extends Component {

    loadData = async () => {
        let data;
        try {
             data = await loadDeviceData("foo"); // example, this would return undefined
        } catch (e) {}

        console.log(data);
    };

    saveData = async () => {

        // This represents your data, this is just a placeholder example.
        const someJSON = [
             { field: 1},
             { field: 2},
             { field: 3}
            // Etc...
        ];

        try {
            await saveDeviceData("foo", someJSON);
        } catch (e) {}
    };

    render () {

        return (
            <>
                <Button onPress={this.saveData} title="Save data"/>
                <Button onPress={this.loadData} title="Load data"/>     
            </>
        );
    }
}

如果您在项目中设置此代码,并在代码段 2 中呈现组件,请单击按钮并观察调试环境提供的任何控制台.

If you set this code up in a project, and rendered the component in snippet 2, click the buttons and observe whatever console is provided by your debugging environment.

如果您需要查询数据,那么我认为您最好使用 SQLite,您可以为此使用另一个库,例如https://github.com/craftzdog/react-native-sqlite-2

If you need to query the data, then you're best bet in my opinion is using SQLite, you could use another library for that, e.g. https://github.com/craftzdog/react-native-sqlite-2

最后,如果您的意思是需要将该数据存储在远程数据库中,例如托管在您自己的服务器上/与您选择的云提供商一起托管,然后您需要查看发出 http POST/PUT 请求以将该数据发布到处理该数据的 API.如果那是您的问题,那么到目前为止还不清楚.如果是,那么看看使用 fetch(见下面的链接)将您的数据发送到您的 API.

Finally, if you mean you need to store that data in a remote database, e.g. hosted on your own server(s) / with your chosen cloud provider, then you'd need to look at making a http POST/PUT request to post that data up to your API that handles that. If that is your question, it's by-far too unclear though. IF it is, then look at using fetch (see link below) to send your data to your API.

https://facebook.github.io/react-native/docs/network

免责声明:以上代码未经测试!

Disclaimer: The code above is untested!

祝你好运!

这篇关于创建 JSON 文件反应原生并加载到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆