我正在學習 React-Native 并嘗試在個人資料螢屏上顯示用戶個人資料。
顯示從服務器獲取的物件串列非常簡單,但我對如何顯示 API 呼叫獲取的單個物件感到困惑。
這是我獲取的物件資料輸出,當我console.log(getProfileApi.data)在顯示它之前正確執行時得到。
Object {
"email": "[email protected]",
"first_name": "User",
"gender": "Male",
"id": 2,
"last_name": "1",
"profile": Object {
"address": null,
"city": null,
"country": null,
"dob": "2021-11-01",
"profile_pic": "http://192.168.0.218:8000/media/profile/user1_profile.jpg",
"title": null,
"zip": null,
},
"user_type": "Owner",
}
這就是我嘗試顯示獲取的資料的方式,但未顯示資料。
<FlatList
// getProfileApi contains the response from server which is shown above
data={getProfileApi.data}
renderItem={({ item }) => (
<Text>{item.email}</Text>
)}
/>
我如何提取資料并顯示它。是否有其他組件可以代替 Flat-List 來顯示單物件資料?
uj5u.com熱心網友回復:
首先,FlatList用于顯示陣列的資料。它通常用于顯示大串列,例如電子商務應用程式中的產品串列、用戶串列、帖子等。要顯示您擁有的簡單資料,您可以使用ScrollView. 按照以下方法在ScrollView.
import React, { useCallback, useEffect, useState } from 'react';
import { View, Text, ScrollView, StyleSheet } from 'react-native';
const YourScreenName = () => {
// declare state variable to handle loading UI
// set initial value to true, so when screen load initially it display loading
const [isLoading, setLoading] = useState(true);
const [user, setUser] = useState(null);
useEffect(() => {
getData();
}, []);
const getData = useCallback(() => {
setLoading(true); // Start the loader, So when you start fetching data, you can display loading UI
getProfileApi().then((data) => {
setUser(data);
setLoading(false);
}).catch((error) => {
// display error
setLoading(false); // stop the loader
})
// or your any data fetching query
// setUser(getProfileApi.data);
// setLoading(false);
}, []);
return (
<ScrollView
style={styles.container}
contentContainerStyle={styles.contentContainer}
>
{
isLoading && (
<Text>Loading</Text>
);
}
{
!isLoading && user && (
<View>
<Text>Email : {user.email}</Text>
<Text>Name : {user.name}</Text>
</View>
)
}
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
contentContainer: {
flexGrow: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
export default YourScreenName;
uj5u.com熱心網友回復:
您可以直接渲染 UI 組件并使其內容動態化,而不是使用平面串列,如下所示
<Text>{getProfileApi.data.email}</Text>
這里不需要平面串列,因為它用于呈現資料串列,但對于單個資料集,您可以直接在 UI 中使用它。
uj5u.com熱心網友回復:
首先創建一個這樣的狀態
const [myArray, setMyArray] = useState([]);
那么你必須在你從你的 api 中獲取資料后將你的陣列設定為狀態,而不是直接呼叫看起來像一個函式的 getProfileApi
setMyArray(yourresponsearray);
然后在您的 Flatlist 組件中,您可以在 data prop 中傳遞該狀態
<FlatList
data={myArray}
renderItem={({ item }) => (
<Text>{item.email}</Text>
)}
/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357556.html
