react-native - 从 api restful 填充 flatlist
问题描述
我正在尝试从我的 api restful 中获取值并加载到我的平面列表中。但它不起作用。
import React from 'react';
import {
Platform,
ScrollView,
StyleSheet,
Text,
View,
FlatList,
Row
} from 'react-native';
export default function HomeScreen() {
const highScores = fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.movies);
return responseJson.movies;
})
.catch((error) => {
console.error(error);
alert(error);
});
return (
<View style={styles.container}>
<ScrollView
style={styles.container}
contentContainerStyle={styles.contentContainer}>
<View>
<FlatList
data={highScores}
renderItem={
({ item, index }) =>
<Row highScore={item} index={index} key={index} />
}
/>
</View>
);
}
看一下,在我将加载到 highScores 并最终填充我的 FlatList 之后,我正在访问https://facebook.github.io/react-native/movies.json以获取他的数据。但它不起作用......有人可以帮我修复它吗?
解决方案
实际上,在渲染之后,您保存高分为时已晚。尝试使用状态和效果挂钩来保存高分并触发重新渲染。
function App() {
const [highScores, setHighScores] = useState([]);
useEffect(() => {
fetch("https://facebook.github.io/react-native/movies.json")
.then(response => response.json())
.then(responseJson => {
console.log(responseJson.movies);
// return responseJson.movies;
setHighScores(responseJson.movies);
})
.catch(error => {
console.error(error);
alert(error);
});
}, []);
return (
<div className="App">
{highScores.map(({ title, releaseYear }, index) => (
<div index={index} key={index}>
{title}: {releaseYear}
</div>
))}
</div>
);
}
推荐阅读
- autodesk-forge - Bim360:从模板创建清单的 API
- python - 在 Python 3 中解码后,多行 base64 字符串仅返回最后一行
- selenium - 使用 Microsoft 测试管理器和 Selenium 实现自动化?
- excel - Application.Match 多列
- android - 为什么 Dialog 不显示 PDFView?
- javascript - 如何删除与自定义属性的整个多对多关系?
- javascript - 从 JavaScript 中的对象数组中删除第一个重复项
- shopify - 收听shopify购物车更新数量
- buildroot - 如何在 BUILDROOT 中更新 SELINUX 的 modules.conf?
- angular - 如何在Angular 8+中获取没有路由的路由的URL