reactjs - 使用 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;
- 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));
};
没有从功能组件返回。有没有人有解决办法。
解决方案
基本上它与从类中调用函数是一样的
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;
推荐阅读
- php - (PHP) 等待子进程超时退出
- angular - 将 FormArray 设置为 FormGroups 数组
- jquery - 逐月更改时替换html文本
- java - Executor Service 任务在 Spring Boot 应用程序中执行两次
- r - r中的线性插值:根据另一列的数据替换一列中的NA
- electron - 将 devtools 中当前选定的元素传递给电子中的 javascript
- reactjs - Firebase redux 数据映射状态到道具?
- python - 从 3D 散点图构建表面,其中 2D 中的 [x,y] 转换为 [f1(x,y),f2(x,y),f3(x,y)]
- excel - 如果两列值匹配,则合并内容
- javascript - 是否可以通过一次回流来进行这些更改?