我正在使用 React Native 構建一個應用程式,并且我想使用來自 Heroku api 的資料。但是,當我進行 API 呼叫并 consolog 資料時,我可以看到資料,但是當我嘗試映射它們時,DOM 沒有任何內容。誰能告訴我我做錯了什么?太感謝了。下面是我的罐頭和螢屏商店。
應用程式.jsx:
import react, { useEffect, useState } from "react";
import { FlatList, useWindowDimensions, View, Text } from "react-native";
import axios from "axios";
const App = () => {
const { height } = useWindowDimensions();
const [places, setPlaces] = useState({});
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
axios
.post(
"https://where2playdk.herokuapp.com/nearest?lat=55.70232019168349&lon=12.561693791177802"
)
.then((response) => console.log(response.data))
.catch((error) => setIsError(error))
.finally(() => setIsLoading(false));
}, []);
return (
<View>
{places.map(({ name, distance }) => (
<View>
<Text>name</Text>
<Text>{name}</Text>
<Text>{distance}</Text>
</View>
))}
</View>
);
};
export default App;

uj5u.com熱心網友回復:
你不是在這里更新狀態,只是安慰資料,
useEffect(() => {
axios
.post(
"https://where2playdk.herokuapp.com/nearest?lat=55.70232019168349&lon=12.561693791177802"
)
.then((response) => setPlaces(response.data)) // here is the
//mistake
.catch((error) => setIsError(error))
.finally(() => setIsLoading(false));
}, []);
uj5u.com熱心網友回復:
我沒有使用過 React Native,但如果它與常規 React 相同,那么我看到的第一個問題是地圖中的每個元素都應該有一個鍵:
{places.map(({ name, distance }) => (
<View key={name}>
{/* ... */}
</View>
))}
您還需要處理加載狀態。因為當 App 第一次運行時,places 是未定義的,所以你正在呼叫undefined.map它可能會拋出一個錯誤。早點回來就夠了。
if (!places) return <Text>Loading...</Text>
而且我也沒有看到setPlaces()被呼叫,我假設你用控制臺日志替換了它?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/528149.html
下一篇:NestJS與客戶端通信
