javascript - 将 JSON 数据传递到另一个屏幕
问题描述
1
我是初学者,仍在学习本机反应。
在我的本机应用程序中,我有 2 个屏幕。在第一页,我有 JSON 数据;我想将此 JSON 数据传递到下一页。
我使用 react-navigation 在页面之间导航。我需要为每本书的新书屏幕传递每个参数。
但我不知道如何将 JSON 数据传递到下一页!在 BookScreen.js 中没有看到函数“getParam”。
第一个屏幕:ExploreScreen.js
import React, { useState, useEffect } from "react";
import {
View,
Text,
StyleSheet,
FlatList,
Image,
TouchableOpacity,
} from "react-native";
export default function ExploreScreen({ navigation, route }) {
const [data, setData] = useState([]);
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
await fetch(
"http://www.json-generator.com/api/json/get/bTvNJudCPS?indent=2"
)
.then((response) => response.json())
.then((receivedData) => setData(receivedData));
};
return (
<View style={styles.container}>
<FlatList
data={data}
renderItem={({ item }) => (
<TouchableOpacity
style={styles.book}
onPress={() => navigation.navigate("Book", item)}
>
<Image
style={styles.bookImage}
source={{ uri: item.book_image }}
></Image>
<View>
<Text style={styles.bookTitleText}>{item.title}</Text>
<Text style={styles.bookAuthor}>{item.author}</Text>
<Text style={styles.bookGenre}>
<Text styles={styles.gen}>Genul: </Text>
{item.genre_id}
</Text>
</View>
</TouchableOpacity>
)}
></FlatList>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
alignSelf: "center",
paddingVertical: "15%",
},
book: {
flex: 1,
flexDirection: "row",
marginBottom: 3,
},
bookImage: {
width: 100,
height: 100,
margin: 5,
},
bookTitleText: {
color: "#8B0000",
fontSize: 15,
fontStyle: "italic",
fontWeight: "bold",
},
bookAuthor: {
color: "#F41313",
},
});
第二个屏幕:BookScreen.js
import React from "react";
import { View, Text, StyleSheet } from "react-native";
export default function BookScreen({ navigation, route }) {
const { item } = route.params;
return (
<View style={styles.container}>
<Text style={styles.text}>{navigation.getParam("name")}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
alignSelf: "center",
paddingVertical: "100%",
},
text: {
fontSize: 20,
},
});
解决方案
在您的 BookScreen 中,将其更改为以下内容:
export default function BookScreen({ navigation, route }) {
const { item } = route.params;
return (
<View style={styles.container}>
<Text style={styles.text}>{item.name}</Text>
</View>
);
}
编辑:我认为你应该像这样传递数据:
navigation.navigate('Book', {item: item});
推荐阅读
- for-loop - 如何对具有二项式协变量数据的模型进行循环线性回归?
- angular - FormGroup 验证器
- owin - 使用 Owin Starup 的 ASP.Net 表单中的授权代码流错误
- spring-boot - Spring boot:我需要几行代码的解释
- ansible - jinja2 模板中的 Ansible 变量
- c# - Rider 终端/控制台未清除 [Linux/C#]
- bazel - 有没有一种简单的方法可以查看 Bazel“Make”变量扩展到什么?
- c# - Unity AI 角色控制器重力
- haskell - haskell 函数,它接受一个整数并以二进制形式返回表示该数字的字符串
- distributed-computing - 在(CAP)一致性与可访问性问题期间,哪些类型的数据会丢失?