簡體   English   中英

React-Native——全局變量不變

[英]React-Native — Global variable not changing

我有兩個單獨的文件,第一個是一個組件 (List.js),它使用第二個 (APIService.js) 來獲取不同的 API。 為了更正獲取,URL 需要接收全局變量。 現在,我試圖從 APIService 文件中的函數重新定義這些變量,但沒有成功。 APIService.js變量在API calls注釋之前被重新定義。

我有兩個問題:

  • 為什么沒有重新定義全局變量naptanId
  • 可以從組件定義和傳遞這些變量嗎?

偽代碼

  • 檢測信標
  • 重新定義 naptanId
  • 使用最近定義的變量的組件獲取 API
  • API調用完成
  • 數據傳回組件
  • 設置狀態

列表.js

componentDidMount() {
    // Executes first function
    APIService._fetchStopPoint((resp1) => {
        console.log("Stoppoint", resp1)
        // ... and set the bus state with the first response
        this.setState({
            bus: resp1
        });

        // ... based on the response, convert array to string
        const lines = (resp1.lines.map((line) => line.name)).toString()

        // ... pass lines to sencond function
        APIService._fetchArrivalTimes(lines, (resp2) => {
            // .. and set the tube state with the second response
            this.setState({
                isLoading: false,
                tube: resp2
            });
        });
    });
}

APIService.js

// Variables 
// ***********************************************************************
let naptanId = undefined
let lines = undefined

let ice = '59333'
let mint = '57011'
let blueberry = '27686'

let nearestBeacon = undefined;
let newBeaconId = undefined;

let setIce = false;
let setBlueberry = false;
let setMint = false;


// Beacon detection
// ***********************************************************************
const region = {
    identifier: 'Estimotes',
    uuid: '354A97D8-9CAF-0DC7-CE0E-02352EBE90CD',
};

// Request for authorization while the app is open
Beacons.requestWhenInUseAuthorization();
Beacons.startMonitoringForRegion(region);
Beacons.startRangingBeaconsInRegion(region);
Beacons.startUpdatingLocation();

// Listen for beacon changes
const subscription = DeviceEventEmitter.addListener('beaconsDidRange', (data) => {

    const ibeacons = data.beacons

    // var lowestAccuracySeen = 0.5;
    let lowestAccuracySeen = "immediate"

    // Check if beacons are updating
    if (ibeacons && ibeacons.length > 0) {
        // Loop through beacons array
        for (var i = 0; i < ibeacons.length ; i++) { 
            // Find beacons with same minor ...
            var foundBeacon = ibeacons.find(function(closestBeacon) {
                // ... and return the beacon the lowest accuracy seen
                // return closestBeacon.accuracy.toFixed(2) < lowestAccuracySeen;
                return closestBeacon.proximity == lowestAccuracySeen
            });
            // If found ...
            if (foundBeacon)    {
                // ... define the lowest accuracy and the nearest beacon
                lowestAccuracySeen = foundBeacon.accuracy;
                nearestBeacon = foundBeacon;

                // Identify what component to render against nearest beacon
                setIce = nearestBeacon.minor == ice ? true : false;
                setMint = nearestBeacon.minor == mint ? true : false;
                setBlueberry = nearestBeacon.minor == blueberry ? true : false;

                if (setIce) {

                    // THESE VARIABLES CANNOT BE REDEFINED
                    naptanId = "490004936E" 
                    lines = "55"

                } else if (setMint) {

                } else if (setBlueberry) {

                };
            }
        }
    }
});

// API calls 
// ***********************************************************************
class APIService {


    // Fecth stop point info
    static _fetchStopPoint(cb) {
        console.log(naptanId, lines)


        fetch(`https://api.tfl.gov.uk/StopPoint/${naptanId}`)
            .then(stopData => {
                try {
                    stopData = JSON.parse(stopData._bodyText); // Converts data to a readable format
                    cb(stopData, naptanId);
                } catch(e) {
                    cb(e);
                }
            })
            .catch(e => cb(e));
    }

    // Fetch arrival times info
    static _fetchArrivalTimes(lines, cb) {

        fetch(`https://api.tfl.gov.uk/Line/${lines}/Arrivals/${naptanId}`)
            .then(arrivalData => {
                try {
                    arrivalData = JSON.parse(arrivalData._bodyText);
                    arrivalTime = arrivalData
                    cb(arrivalData);
                } catch(e) {
                    cb(e);
                }
            })
            .catch(e => cb(e));
    }

    // Fetch status info
    static _fetchStatus(lines) {

        fetch(`https://api-argon.digital.tfl.gov.uk/Line/${lines}/Status`)
            .then(statusData => {
                try {
                    statusData = JSON.parse(statusData._bodyText); // Converts data to a readable format
                    cb(statusData);
                } catch(e) {
                    cb(e);
                }
            })
            .catch(e => cb(e));
    }

}

module.exports = APIService;

處理這些全局變量(跨不同組件)的最簡單方法是使用AsyncStorage

let response = await AsyncStorage.getItem('listOfTasks');  //get, in any components
AsyncStorage.setItem('listOfTasks', 'I like to save it.'); //set, in any components

對於性能更重要的全局變量,您還可以考慮Realm Database (如 iOS 和 Android 中的 CoreData、SQLite)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM