[英]React Native : multiple renders at fetching data with useEffect hook
我的代码有两个问题。 第一个是数据未定义,我不是从 API 获取数据。 第二个是钩子 useEffect 它没有像 componendidmount 那样工作,并且它在循环重新渲染组件。 这是我的代码:
import { StatusBar } from 'expo-status-bar';
import React ,{useState,useEffect} from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default function App() {
const [loading, setLoading] = useState(true);
const [users, setUsers] = useState([]);
const fetch = async () =>{
try{
let data = await fetch("https://api.sampleapis.com/coffee/hot", {method: 'GET'});
let json = await data.json();
setUsers(json);
setLoading(false);
}
catch(err){
console.log("Im catching the error");
console.log(err);
setUsers([]);
setLoading(false);
}
}
useEffect(() => {
fetch();
},[])
return (
<View style={styles.container}>
{loading?<><Text>Loading...</Text></>:<Text>Data fetched</Text>}
</View>
);
}
....
const fetch = async () =>{
....
fetch 方法正在调用自身,尝试更改方法名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.