React-Native — Promise设置和数据处理 [英] React-Native — Promise setup e data handling

查看:169
本文介绍了React-Native — Promise设置和数据处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解开发人员如何将Promise与React-Native结合使用.获得有关如何设置API调用和处理数据的反馈和建议,将是很棒的.请了解我以前从未使用过Promise,而且我是React-Native的新手.

I am trying to understand how developers use Promise with React-Native. It would be great to get feedback and recommendations on how to setup API calls and handle the data. Please understand I never used Promise before and that I am new to React-Native.

先谢谢您.也欢迎您提供有关此主题的任何资源.

Thank you in advance. Any resource about this subject is welcome too.

伪代码

孩子

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

父母

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

APIservice.js

孩子

在单独的文件中设置所有API调用是一种好习惯吗?将来我可能需要进行不同的API调用,您是否会创建多个函数来处理该问题?

Is it a good practice to setup all your API calls in a separate file? It's likely that in the future I will need to make different API calls, would you create multiple functions to handle that?

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

App.js

父母

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

As you can see, the way I setup the endpoint is lame. It's not ideal as the URL is the same. I want to structure something that can receive two variables and build the URL on the go. Something like https://api.tfl.gov.uk/Line/${routeid}/Arrivals/${stationid}.

如果我能做到这一点,如何将API调用传递给只有一个endpoint的API服务,该endpoint会根据接收到的两个变量而动态变化?我不确定如何区分仅具有一个" URL的Promise.all中的呼叫.

If I manage that, how can I pass the API call to the APIservice having only one endpoint that dynamically will change based on the two variables it receives? I am not sure how to differentiate the call in the Promise.all having only "one" URL.

这给我带来了另一个问题.在App.js中设置状态时,是否应该使用来自数据的specifics数组来设置状态? bus: data[0]tube: data[1]之类的东西.这是一个好习惯吗?

That brings me another issue. When setting the state in App.js, should I setState using the specifics array from data? Something like bus: data[0], tube: data[1]. Is this a good practice?

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'


let loadData = (endPoint) => {

  // Multiple API calls
  Promise.all([
    APIservice._getStopPoint(endpoint),
    APIservice._getStopPoint(endpoint1),
  ])
  .then((data) => {
    console.log("App.js", data)
  })
  .catch((error) => {
    console.log(error)
  })
}

export default class App extends Component {

  componentWillMount() {
    // URL fetch based on variables, not dynamic
    loadData(endpoint)
    loadData(endpoint1)
  }

  render() {
    loadData("hello")
    return (
      <View style={styles.container}>
        <Text>
          Promise
        </Text>
      </View>
    );
  }
}

推荐答案

您可以尝试以下示例

const callbackFn = (firstName, callback) => {
setTimeout(() => {
if (!firstName) return callback(new Error('no first name 
passed in!'))

const fullName = `${firstName} Doe`

return callback(fullName)
  }, 2000)
}

callbackFn('John', console.log)
callbackFn(null, console.log)

这篇关于React-Native — Promise设置和数据处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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