首页 > 解决方案 > 将 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,
  },
});

标签: javascriptjsonreact-nativenavigationparameter-passing

解决方案


在您的 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});

推荐阅读