簡體   English   中英

如何在 React 中編寫服務類型的函數,該函數可以使用函數的輸入參數獲取然后返回數據

[英]how to write service kind of function in React which can fetch then return data using input params of function

我是 React 和 Angular 背景的新手。 我試圖編寫可重用的函數,該函數可以使用輸入(國家代碼)處理 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'))

}
}

我越來越“未定義”。 我知道我在這里有兩個問題。 一是如何從APIService函數返回數據二是如何讓組件等待數據到來。

我也試過 componentDidMount() 。 但沒有工作。 想要簡化流程,所以不想在組件中放置任何 JSX 語法來傳遞道具方面的參數。

接口管理器

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')
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM