即使数据可用,React Native 也不会渲染道具

React Native not rendering prop even though data is available

我刚刚使用选项卡式视图模板启动了一个基本的 React Native 应用程序。我需要能够对某些数据发出 http get 请求,我使用文档中的示例作为起点。在同一组件中渲染效果很好。我正在尝试为列表项创建另一个组件并将数据作为道具从 parent.

传递

Parent:

  const [isLoading, setLoading] = React.useState(true);
  const [data, setData] = React.useState([]);

  React.useEffect(() => {
    const abortController = new AbortController();
    const signal = abortController.signal;
    fetch("https://reactnative.dev/movies.json", { signal: signal })
      .then((response) => response.json())
      .then((json) => setData(json.movies))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));

    return function cleanup() {
      abortController.abort();
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Tab Mars One</Text>
      <View
        style={styles.separator}
        lightColor="#eee"
        darkColor="rgba(255,255,255,0.1)"
      />
      {isLoading ? (
        <ActivityIndicator />
      ) : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Post item={item} />
          )}
        />
      )}
    </View>
  );
}

Child:

const Post = (item) => {
    console.log(item)
  return (
    <TouchableOpacity>
      <View>
        <Text>{item.title}</Text>
      </View>
    </TouchableOpacity>
  );
};

当我 运行 这样做时,根本没有任何渲染。没有控制台错误。控制台记录 Post 组件中的项目正在记录 API 中的正确项目,所以我知道数据在那里并且格式正确但没有呈现任何内容。这些是我在项目中编辑过的唯一文件,所以我不确定问题出在哪里或我遗漏了什么。请指教

问题

您已将数据传递给道具 item,但在 Post 中命名了 整个 道具对象 item

解决方案

Post 需要从 props 中解构 item

const Post = ({ item }) => {
  console.log(item)
  return (
    <TouchableOpacity>
      <View>
        <Text>{item.title}</Text>
      </View>
    </TouchableOpacity>
  );
};

Expo Snack