繁体   English   中英

React-Native —使用Promise为API请求构建动态URL

[英]React-Native — Building a dynamic URL for API requests using Promise

我将较大的帖子分解为较小的问题。 请了解我以前从未使用过Promise,而且我也是React-Native的新手。 获得有关如何设置API调用和处理数据的反馈和建议,将是很棒的。 先感谢您。

如何为API请求动态创建URL? 这是我想要实现的目标:

伪代码

儿童

  • 检索两个变量
  • 使用这两个变量来构建URL
  • 触发第一个承诺并解决
  • 检索另外两个变量
  • 使用这两个变量来构建新的URL
  • 触发第二个承诺并解决
  • 收集来自两个诺言的数据并传递给父项

  • 从Child检索数据
  • 从第一个Promise中获取数据并设置为状态
  • 从第二个Promise获取数据并设置为另一个状态

APIservice.js

儿童

class APIservice {


    _getStopPoint = (endpoint) => {
        return new Promise(function(resolve, reject) {
            fetch(endpoint)
            .then((response) => response.json())
            .then((data) => {
                console.log("APIservice StopPoint", data)
                resolve(data);
            });
        });
    };
};


module.exports = new APIservice

List.js

如您所见,设置端点的方式很la脚。 由于网址相同,因此不太理想。 我想构造一些可以接收两个变量的东西,并随时随地构建URL。 类似于https://api.tfl.gov.uk/Line/${routeid}/Arrivals/${stationid}

如果我能做到这一点,如何将API调用传递给APIservice,使其只有一个端点会根据接收到的两个变量动态变化? 我不确定如何区分Promise.all中只有“一个” URL的呼叫。

let APIservice = require('./APIservice')

let endpoint = 'https://api.tfl.gov.uk/Line/55/Arrivals/490004936E'
let endpoint1 = 'https://api.tfl.gov.uk/Line/Northern/Arrivals/940GZZLUODS'

export class List extends Component {
    constructor(props) {
        super(props);

        this.state = {
            bus: null,
            tube: null,
        }
    };

    componentWillMount() {
        let loadData = (endPoint) => {

            Promise.all([
                APIservice._getStopPoint(endpoint),
                APIservice._getStopPoint(endpoint1),
            ])
            .then((data) => {

                // Name for better identification
                const listBus = data[0]
                const listTube = data[1]

                this.setState({
                    bus: listBus,
                    tube: listTube
                }, () => {
                    console.log("bus", this.state.bus, "tube", this.state.tube)
                });
            })
            .catch((error) => {
                console.log(error)
            })
        }

        loadData(endpoint);
        loadData(endpoint1);

    }

    render() {
        return(
            <View>
                <FlatList 
                data={this.state.bus}
                renderItem={({item}) => (
                    <Text>{item.timeToStation}</ Text>
                )}
                keyExtractor={item => item.id}
                />
                <FlatList 
                data={this.state.tube}
                renderItem={({item}) => (
                    <Text>{item.timeToStation}</ Text>
                )}
                keyExtractor={item => item.id}
                />
            </ View>
        );
    }
};

一旦理解了它的工作原理,就很容易实现您所说的话。

您正在对API调用使用fetch Promise ,使用时会返回Promise 您的用例的伪代码将如下所示:

class APIService {
    static fetchFirst(cb) {
        fetch('FIRST_URL')
            .then(resp => {
                try {
                    resp = JSON.parse(resp._bodyText);
                    cb(resp);
                } catch(e) {
                    cb(e);
                }
            })
            .catch(e => cb(e));
    }

    static fetchSecond(routeid, stationid, cb) {
        fetch(`https://api.tfl.gov.uk/Line/${routeid}/Arrivals/${stationid}`)
            .then(resp => {
                try {
                    resp = JSON.parse(resp._bodyText);
                    cb(resp);
                } catch(e) {
                    cb(e);
                }
            })
            .catch(e => cb(e));
    }
}

module.exports = APIService;

将此包含在您的父组件中,并按以下方式使用它:

let APIService = require('./APIService')

export class List extends Component {
    constructor(props) {
        super(props);

        this.state = {
            bus: null,
            tube: null,
        }
    };

    componentWillMount() {
        APIService.fetchFirst((resp1) => {
            APIService.fetchSecond(resp1.routeid, resp1.stationid, (resp2) => {
                this.setState({
                    tube: resp2
                });
            });
        });
    }

    render() {
        return(
            <View>
                <FlatList 
                data={this.state.bus}
                renderItem={({item}) => (
                    <Text>{item.timeToStation}</ Text>
                )}
                keyExtractor={item => item.id}
                />
                <FlatList 
                data={this.state.tube}
                renderItem={({item}) => (
                    <Text>{item.timeToStation}</ Text>
                )}
                keyExtractor={item => item.id}
                />
            </ View>
        );
    }
};

我尚未检查回调函数中的错误,请注意使用此错误时已处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM