首页 > 解决方案 > 是否可以在它所在的类之外的异步函数中传递数据?

问题描述

我正在使用 Ionic React 和 Capacitor 来尝试提取地理位置,然后尝试将其存储在数据库中。我正在尝试将值存储在 App.coordinate 中,但每当我尝试将其导出到 map.ts 时,它都会将其作为未定义存储在数据库中。

无论如何要将 getCurrentPosition() 函数中的地理位置数据传递给 map.ts?

如您所见,我尝试了多种方法来尝试传递数据(如静态坐标/坐标!变量所见)。

应用程序.tsx

import * as React from 'react';
import { Plugins } from '@capacitor/core';
import { all } from '../server/db/maps';
const { Geolocation } = Plugins;

export class App extends React.Component<IAppProps, IAppState> {
    state: any = {};
    props: any = {};
    lat!: number;
    long!: number;
    static coordinate: string;
    coord!: string;

    constructor(props: any) {
        super(props);
        this.state = { maps: [] };
        this.getCurrentPosition();
    }

    async getCurrentPosition() {
        const position = await Geolocation.getCurrentPosition();
        this.lat = position.coords.latitude;
        this.long = position.coords.longitude;
        this.coord = "[" + this.long + ", " + this.lat + "]";
        App.coordinate = "[" + this.long + ", " + this.lat + "]";
        console.log('Current', App.coordinate);
    }

    async componentDidMount() {
        try {
            let r = await fetch('/api/maps');
            let maps = await r.json();
            this.setState({ maps });
        } catch (error) { console.log(error); }
    }

    render() {
        return (
            <main className="container my-5">
                <h1 className="text-primary text-center">Geolocation</h1>
                <ul className="list-group">
                    {this.state.maps.map(maps =>{ return <li className="list-group-item">{maps.id}, {maps.date}, {maps.coordinates} </li> })}
                </ul>
            </main>
        );
    }
}

export let Coordinates = App.coordinate; //App.coordinate passes on undefined
export interface IAppProps {}
export interface IAppState { maps: Array<{ id: string, date: Date, coordinates: string }>; }
export default App;

地图.ts

import { Connection } from './index';
import { App, Coordinates } from '../../client/app';

export const all = async() => {
    return new Promise((resolve, reject) => {
        Connection.query('SELECT * FROM COORDINATES', (err, results) => {

            if(err){
                return reject(err);
            }
            resolve(results);
        });

        let stmt = 'INSERT INTO COORDINATES (id, date, coordinates) VALUES ? ';
        let todos = [['3343', '2020-01-09 22:00:00', '[44.44444, 55.55555]'],
                     ['5555', '2020-01-09 22:01:00', Coordinates]];
        Connection.query(stmt, [todos], (err, results, fields) => {
            if (err) {
              return console.error(err.message);
            }
            // get inserted rows
            console.log('Row inserted:' + results.affectedRows);
          });
    });
}

export default {
    all
}

标签: javascriptmysqlionic-frameworkgeolocationcapacitor

解决方案


以你试图做的方式,行不通

为什么?

因为您需要 App 类的实例来访问其“坐标”。即使您使用的是静态变量,该变量也只是动态填充,而不是静态填充。

如何解决?

您只能通过动态调用方法来存储坐标,并将插入逻辑与列表逻辑分开来解决这个问题。

看:

export const all = async() => (
    new Promise((resolve, reject) =>
        Connection.query('SELECT * FROM COORDINATES', (err, results) => {
            if(err){
                return reject(err);
            }
            resolve(results);
        })
)

export const save = async (coordinates) => (
    new Promise((resolve, reject) => {
        // Make use of const variables as well
        const stmt = 'INSERT INTO COORDINATES (id, date, coordinates) VALUES ? ';
        const todos = [['3343', '2020-01-09 22:00:00', '[44.44444, 55.55555]'],
                     ['5555', '2020-01-09 22:01:00', coordinates]]; // dynamic variable, not static.
        Connection.query(stmt, [todos], (err, results, fields) => {
            if (err) {
              return console.error(err.message);
            }
            // get inserted rows
            console.log('Row inserted:' + results.affectedRows);
          });
    });
)

然后,您可以从 App 调用它,最好在 componentDidMount 上调用它(因为它是一个异步函数)

async componentDidMount() {
    try {
        let r = await fetch('/api/maps');
        let maps = await r.json();
        this.setState({ maps });
        await this.getCurrentPosition()
        // ... call to server to save this.coord
    } catch (error) { console.log(error); }
}

async getCurrentPosition() {
    const position = await Geolocation.getCurrentPosition();
    this.lat = position.coords.latitude;
    this.long = position.coords.longitude;
    this.coord = "[" + this.long + ", " + this.lat + "]";
    console.log('this.coord', this.coord);
}

推荐阅读