简体   繁体   English

使用 Native React 中的 Fetch 从 API 中提取数据

[英]Issue pulling data from API using Fetch in Native React

 const [data, setData] = useState(null); var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); var raw = JSON.stringify({ "CariId": 2, "CariBakiyeyeSadeceOnayliFaturalarYansisin": false, "DonemId": 1, "BasTarih": "01.01.2021", "BitTarih": "01.01.2023" }); var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; useEffect(() => { const fetchData = async () => { const response = await fetch("http://192.168.1.30:2828/CodesAndroid.svc/CariHesapListesiDetayli", requestOptions); const result = await response.text(); const parsedResult=JSON.parse(result); const deneme =JSON.parse(parsedResult) setData(parsedResult); }; fetchData(); }, []);

 <View style={{flex:0.5}}> <FlatList data={data} renderItem={({ item }) => ( <View > <Text style={{color:'red'}}>{data}</Text> </View> )} keyExtractor={item => item.CariId}/> </View>

I can get the data from the API with the help of Javascript, but I don't know how to get it one by one?我可以借助Javascript从API中获取数据,但我不知道如何一一获取? My research has yielded no results.我的研究没有结果。 I would be very happy if you could help.如果你能帮忙,我会很高兴。 Thanks...谢谢...

I think your error has nothing to do with your fetch and more to do with data initialized to null here:我认为你的错误与你的获取无关,更多的是与这里初始化为 null 的数据有关:

const [data, setData] = useState(null);

On the first render null doesn't have a map property.在第一次渲染时,null 没有 map 属性。 So I think it is throwing an error before the fetch can even complete.所以我认为它甚至在提取完成之前就抛出了一个错误。 So if you initialize it to所以如果你将它初始化为

const [data, setData] = useState([]);

that should get you pass the first render.那应该让你通过第一个渲染。 After that you can figure out if your fetch is the issue之后你可以弄清楚你的提取是否是问题所在

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM