React-Native - 全局变量不变

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React-Native - 全局变量不变相关的知识,希望对你有一定的参考价值。

我有两个单独的文件,第一个是使用第二个(APIService.js)来获取不同API的组件(List.js)。要更正提取,URL需要接收全局变量。现在,我试图从APIService文件中的函数重新定义这些变量,但没有成功。在APIService.js评论之前,API calls正在重新定义变量。

我有两个问题:

  • 为什么全局变量naptanId没有被重新定义?
  • 可以从组件中定义和传递这些变量吗?

伪代码

  • 检测信标
  • 重新定义naptanId
  • 使用最近定义的变量获取组件API
  • API调用已完成
  • 数据传递回Component
  • 设置状态

List.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(与iosandroid中的Coreite,SQLite一样)。

以上是关于React-Native - 全局变量不变的主要内容,如果未能解决你的问题,请参考以下文章

C#-WebForm-★内置对象简介★Request-获取请求对象Response相应请求对象Session全局变量(私有)Cookie全局变量(私有)Application全局公共变量Vi(代码片段

JavaScript 全局变量不变

使用自定义输入组件时的 React-Native 不变违规

片段 - 全局视图变量与本地和内部类侦听器和内存泄漏

如何使全局变量在多个 google appengine 实例上保持不变?

python函数中局部变量与全局变量遵守规则