如何在 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 个问题。 一是如何从API服务函数返回数据 其次是如何让组件等到数据到来。

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

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

获取数据.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>
)
}
}

APIService.js

export default class APIService {
static classInstance = null;
static getAPIServiceInstance() {
if (APIService.classInstance === null) {
APIService.classInstance = new APIService();
}
return this.classInstance;
}
callAPI(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>)
})
}
}

最新消息.js

import React from 'react';
import APIService from '../APIService/APIService';
export default class LatestNews extends React.Component {
constructor(){}
componentWillMount(){
var result= APIService.getAPIServiceInstance().callAPI('us')
}
}

相关内容

最新更新