首页 > 解决方案 > 如何在 React 中编写服务类型的函数,该函数可以使用函数的输入参数获取然后返回数据

问题描述

我是 React 的新手,来自角度背景。我试图编写可重用函数,该函数可以使用输入(国家代码)处理 API 调用,并可以将数据返回到组件。这样我就可以根据我的需要在侧面组件中使用该数据。

import React, {Component} from 'react';
const APIService=function(countrycode){
let newsData=[];
fetch(process.env.REACT_APP_API_URL+'top-headlines? 
   country='+countrycode+'&apiKey='+process.env.REACT_APP_API_KEY)
   .then((responce) =>{
  return responce.json()
}).then(data => {
  newsData=data;
  //Got data hear
  console.log(data);
 return newsData
}).catch(error=>{
  return(<div>Somethinhg went wrong. Sorry forinconvinance</div>)
})
}
export  default APIService;

在我的组件旁边

import React from 'react';
import APIService from '../APIService/APIService';
export default class LatestNews extends React.Component {
constructor(){}

componentWillMount(){
//Not getting Data hear
console.log(APIService('us'))

}
}

我越来越“未定义”。我知道我在这里有 2 个问题。一是如何从 APIService 函数返回数据二是如何使组件等待数据到来。

我也尝试了 componentDidMount() 。但没有奏效。想要简化流程,所以不想在组件中放入任何 JSX 语法来传递参数方面的 props。

标签: reactjsreact-native

解决方案


ApiManager.js

export class ApiManager extends Component {
static myInstance = null;

static getInstance() {  
    return new ApiManager();
}
async getMoviesFromApiAsync(countryCode) {
    try {
        let response = await fetch(
            'https://restcountries.eu/rest/v2/callingcode/'+countryCode,
        );
        let responseJson = await response.json();
        return responseJson;
    } catch (error) {
        console.error(error);
    }
}
}
export default ApiManager

FetchData.js

import React, { Component } from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import ApiManager from '../utils/ApiManager';
export default class FetchData extends Component {
constructor(props) {
    super(props)
    this.state = {
        resultArr: []
    }
}

callApi() {
    //Call Api with parameter 91 as countryCode
    ApiManager.getInstance().getMoviesFromApiAsync(91).then((result) => {
        console.log('result from API ====>', result)
        this.setState({ resultArr: result });
    });
}
render() {
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <TouchableOpacity style={{ backgroundColor: 'green', padding: 20 }} onPress={() => this.callApi()}>
                <Text style={{ color: 'white' }}> Fetch Data </Text>
            </TouchableOpacity>
            <Text>{JSON.stringify(this.state.resultArr[0])}</Text>
        </View>
    )
}
}

推荐阅读