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

时间:2020-07-31 21:34:33

标签: reactjs react-native react-props react-functional-component

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

父母:

  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>
  );
}

孩子:

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

运行此命令时,没有任何渲染。没有控制台错误。在Post组件中记录该项目的控制台正在从API记录正确的项目,因此我知道数据已经存在并且格式正确,但是没有呈现任何内容。这些是我在项目中编辑过的唯一文件,因此我不确定问题出在哪里或缺少什么。请告知。

1 个答案:

答案 0 :(得分:1)

问题

您已将数据传递给道具import React from "react"; export default React.memo(({ speaker, clickFunction }) => { console.log(`speaker ${speaker.id} ${speaker.name} ${speaker.favorite}`); return ( <button onClick={() => { clickFunction(speaker.id); }} > {speaker.name} {speaker.id} {speaker.favorite === true ? "true" : "false"} </button> ); }); ,但在item中,名称为 entire 道具对象Post

解决方案

item需要从道具中破坏Post

item

Expo Snack