有人在功能组件内部使用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;
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));
};
什么都没有从功能组件返回。有没有人解决。
答案 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;