首页 > 解决方案 > 使用 useEffect 挂钩调用位于功能组件外部的服务文件夹中的 API 端点

问题描述

有没有人在功能组件中使用 useEffect 挂钩作为服务文件夹中的服务而不是直接来自同一个功能组件的功能组件的一个很好的例子,这可以执行吗?我正在尝试执行此 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));
};

没有从功能组件返回。有没有人有解决办法。

标签: reactjsreact-native

解决方案


基本上它与从类中调用函数是一样的

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;

推荐阅读