Android 如何在React Native中显示平面列表中的数据
我正在学习react native,并尝试从API获取数据,并将其显示在平面列表中,但我不知道如何在functional component中实现这一点,因为我已经在internet上阅读了许多教程,但它们都使用基于类的组件 下面是我的代码:Android 如何在React Native中显示平面列表中的数据,android,reactjs,react-native,Android,Reactjs,React Native,我正在学习react native,并尝试从API获取数据,并将其显示在平面列表中,但我不知道如何在functional component中实现这一点,因为我已经在internet上阅读了许多教程,但它们都使用基于类的组件 下面是我的代码: import React, {useEffect,useState} from 'react'; import {View,Text,StyleSheet} from 'react-native'; const List = () => { co
import React, {useEffect,useState} from 'react';
import {View,Text,StyleSheet} from 'react-native';
const List = () => {
const[post,setPost] = useState([]);
useEffect(() => {
const url = 'http://api.duckduckgo.com/?q=simpsons+characters&format=json';
fetch(url).then((res) => res.json())
.then((resp) => console.warn(resp))
.catch((err) => console.warn(err));
},[]);
return(
<View>
<Text style={styles.textStyle}>Hello there</Text>
</View>
);
};
const styles = StyleSheet.create({
testStyle:{
flex: 1,
justifyContent:"center",
alignItems:"center"
}
});
export default List;
import React,{useffect,useState}来自“React”;
从“react native”导入{View,Text,StyleSheet};
常量列表=()=>{
const[post,setPost]=useState([]);
useffect(()=>{
常量url=http://api.duckduckgo.com/?q=simpsons+characters&format=json';
fetch(url).then((res)=>res.json())
.然后((resp)=>控制台警告(resp))
.catch((err)=>console.warn(err));
},[]);
返回(
你好
);
};
const styles=StyleSheet.create({
测试样式:{
弹性:1,
辩护内容:“中心”,
对齐项目:“中心”
}
});
导出默认列表;
我已成功从服务器检索到数据,但如何在平面列表中显示此数据。首先,您需要将响应保存在您的状态中,以供以后参考。然后使用react native的Flatlist组件
const List = () => {
const[post,setPost] = useState([]);
useEffect(() => {
const url = 'http://api.duckduckgo.com/?q=simpsons+characters&format=json';
fetch(url).then((res) => res.json())
.then((resp) => setPost(resp.RelatedTopics))
.catch((err) => console.warn(err));
},[]);
const renderItem = ({ item }) => (
<Text style={styles.textStyle}>{item.Text}</Text>
);
return(
<View>
<FlatList
data={post}
renderItem={renderItem}
keyExtractor={item => item.FirstURL}
/>
</View>
);
};
const List=()=>{
const[post,setPost]=useState([]);
useffect(()=>{
常量url=http://api.duckduckgo.com/?q=simpsons+characters&format=json';
fetch(url).then((res)=>res.json())
.然后((响应)=>setPost(响应相关主题))
.catch((err)=>console.warn(err));
},[]);
常量renderItem=({item})=>(
{item.Text}
);
返回(
item.FirstURL}
/>
);
};
有关更多详细信息,请参阅。首先,您需要查看文档。当我开始玩FlatList时,我没有阅读文档,而是编写了自己的错误代码来找出屏幕上的项目。当我试着让它不那么麻烦的时候,我发现了一个非常简单的方法。我保证这会节省你的时间 这么说来,你会想要一些东西
const数据=[
{姓名:“哈利波特”,电话:1234},
{姓名:“罗恩·韦斯莱”,电话:4321}
]
您的renderItem组件可能如下所示:
constrenderitem=({index,item})=>{
let style=[{fontSize:14}]
//如果第一个项目在顶部给出间距
如果(索引==0)
style.push({paddingTop:5})
报税表(
名称:{item.Name}
电话:{item.Phone}
)
})
item.id | |“哈利波特角色”+i}
/>