簡體   English   中英

FlatList沒有在React Native的子組件中呈現父組件數據

[英]FlatList not rendering parent component data in child component in React Native

我目前正在從我的服務器獲取數據並將其保存在父組件的 UseState 中並將其傳遞給我的子組件。 我在執行 console.log 時看到數據正在傳遞,但是當我嘗試使用 FlatList 渲染它時,我得到了這個錯誤以及整個列表中沒有任何數據在此處輸入圖像描述

這是我用來撥打電話的代碼,我在“infoDisplay”中返回平面列表,具體取決於選擇的選項

 const games = ({item}) => ( <View style={styles.gameContainer}> <Text style={styles.gTitle}> <Text style={styles.gConTitle}>Title: </Text>{item.Title}</Text> <Text style={styles.gInfo}><Text style={styles.gConTitle}>Release Date: </Text>{item.Year}</Text> <Text style={styles.gInfo}><Text style={styles.gConTitle}>Genre: </Text>{item.Genre}</Text> </View> ); if(props.name == 'Games'){ console.log("props.parentToChild: ", props.parentToChild) alert(props.parentToChild) infoDisplay = <FlatList data={props.parentToChild} renderItem={games} keyExtractor={item => item.id}/> }
這是我要處理的數據片段: 在此處輸入圖像描述

我已經修復了你的代碼,這是它的沙盒鏈接https://codesandbox.io/s/wizardly-sid-wuz4v?file=/src/App.js

你可以在你的日志和你的 ChildComponent 的渲染中擁有你想要的數據,警告是因為你沒有為 FlatList 或其項目的視圖提供密鑰。

import React, { useEffect, useState } from "react";
import { StyleSheet, Text, View, FlatList } from "react-native";

function ChildComponent(props) {
  const games = ({ item }) => (
    <View key={item.id} style={styles.gameContainer}>
      <Text style={styles.gTitle}>
        <Text style={styles.gConTitle}>Title: </Text>
        {item.Title}
      </Text>
      <Text style={styles.gInfo}>
        <Text style={styles.gConTitle}>Release Date: </Text>
        {item.Year}
      </Text>
      <Text style={styles.gInfo}>
        <Text style={styles.gConTitle}>Genre: </Text>
        {item.Genre}
      </Text>
    </View>
  );

  if (props.name === "Games") {
    console.log("props.parentToChild: ", props.parentToChild);
  }

  return (
    <FlatList
      key={props.id}
      data={props.parentToChild}
      renderItem={games}
      keyExtractor={(item) => item.id}
    />
  );
}

function App() {
  const [parentToChildState, setParentToChildState] = useState(null);

  useEffect(() => {
    const parentToChild = [
      {
        id: 0,
        Title: "Rise of the Tomb Raider",
        Year: "2016-02-09",
        Genre: "action-adyenture"
      },
      { id: 1, Title: "Death Stranding", Year: "2019-11-08", Genre: "action" }
    ];

    setParentToChildState(parentToChild);
  }, []);

  return <ChildComponent name="Games" parentToChild={parentToChildState} />;
}

const styles = StyleSheet.create({});

export default App;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM