reactjs - 如何在 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。
解决方案
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>
)
}
}
推荐阅读
- android - Android 工作简介:android.intent.action.DATA_SMS_RECEIVED 从未被解雇
- rust - Iterator::collect 函数是如何工作的?
- lua - 如何在表格中打印表格的内容?[卢阿]
- c# - 使用 Open XML 将 XML 文件中的数据读取到 word 文档中创建一个表
- sql - PostgreSQL 简单查询
- types - 如何检测存储在数组中的任何类型的变量 - Godot?
- java - 将 Flutter app facebook 身份验证与 Keycloak 服务集成
- javascript - React-native 和 AXIOS 上的条件渲染问题
- node.js - Sequelize findAll order by value position
- reactjs - ThemeProvider 影响非包装组件