使用useEffect钩子调用位于功能组件外部的服务文件夹中的API端点

时间:2020-04-17 12:39:15

标签: reactjs react-native

有人在功能组件内部使用useEffect挂钩的好例子,该挂钩通过服务文件夹(而不是直接从同一功能组件)作为服务从服务文件夹连接到API端点,是否可以执行?我正在尝试执行此 ShopScreen.js正在从服务文件夹调用fetchShops.js

ShopScreen.js

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import { fetchShops } from '../services/fetchShops';
//import {set} from "react-native-reanimated";

const ShopsScreen = props => {
    const [shops, setShops] = useState([]);

    useEffect(() => {
        fetchShops();
    }, []);

    return(
        <View>
            <Text>The Shops Screen!</Text>
                <Text>{console.log(shops.result[0])}</Text>
        </View>
    );
};

const styles = StyleSheet.create({
    screen: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
});

export default ShopsScreen;
  1. fetchShops.js调用API
export const fetchShops = () => {
    const URL = `https://jsonplaceholder.typicode.com/todos`;
    let data = {};
    return data = fetch(URL)
        .then(response => response.json())
        .then(data => console.log(data));
};

什么都没有从功能组件返回。有没有人解决。

1 个答案:

答案 0 :(得分:1)

基本上,这与从类中调用函数相同

Example.service.js

export const myApi = () => //you can declare here your axios or fetch call..

功能组件

import { myApi } from 'Example.service'; //import my Api from services folder

const MyComponent = () => {
   useEffect(() => {
      myApi().then(res => {
         // you res here
         )
   }, [])
}

编辑:

您没有使用setShops在此处设置数据! 试试这个代码

fetchShops.js:

export const fetchShops = () => {
    const URL = `https://jsonplaceholder.typicode.com/todos`;
    return fetch(URL);
};

ShopScreen.js:

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import { fetchShops } from '../services/fetchShops';
//import {set} from "react-native-reanimated";

const ShopsScreen = props => {
    const [shops, setShops] = useState([]);

    useEffect(() => {
        fetchShops()
            .then(response => response.json())
        .then(data => setShops(data));
    }, []);

    return(
        <View>
            <Text>The Shops Screen!</Text>
                <Text>{console.log(shops.result[0])}</Text>
        </View>
    );
};

const styles = StyleSheet.create({
    screen: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
});

export default ShopsScreen;