显示来自网络 json 文件的 SectionList

Display SectionList from networks json file

我想显示 raddit 站点中的热门站点和有争议站点的列表。我能够使用注释掉的 FlatList 显示数据,但不能使用 SectionList。 数据我设置了data.data,个人认为设置数据是正确的。但是它给出了一个错误。

export default function App() {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState({ title: "", data: [] });
  const width = Dimensions.get("window").width;

  const renderItem = ({ item }) => {
    console.log({ item });
    return (
      <View style={styles.item}>
        <Image style={styles.image} source={{ uri: item.data.thumbnail }} />
        <View style={{ flex: 1, flexDirection: "column" }}>
          <Text style={{ width: width - 50 }}>{item.data.title}</Text>
          <Text style={{ color: "#ababab", fontSize: 10 }}>
            {item.data.domain}
          </Text>
        </View>
      </View>
    );
  };
  const renderSectionHeader = ({ section }) => {
    return <Text>{section.title}</Text>;
  };
  const keyExtractor = (item, index) => item + index;

  useEffect(() => {
    const dataGet = async () => {
      try {
        const res1 = await fetch("https://www.reddit.com/r/newsokur/hot.json");
        const json1 = await res1.json();
        const res2 = await fetch(
          "https://www.reddit.com/r/newsokur/controversial.json"
        );
        const json2 = await res2.json();
        setData({ title: "popular", data: json1.data.children.slice(0, 5) });
        setData({ title: "controversial", data: json2.data.children.slice(0, 5) });
        setLoading(false);
      } catch (err) {
        console.log(err);
      }
    };
    dataGet();
  }, []);

  return (
    <View style={styles.container}>
      {isLoading ? (
        <ActivityIndicator
          style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
          size="large"
          color="#0000ff"
        />
      ) : (
        <SectionList
          sections={data.data}
          keyExtractor={keyExtractor}
          renderItem={renderItem}
          renderSectionHeader={renderSectionHeader}
        />
        /* <FlatList
          data={data.data}
          renderItem={renderItem}
          keyExtractor={keyExtractor}
        /> */
      )}
    </View>
  );
}

下面是一个样式的定义sheet.

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight || 0,
    flexDirection: "column",
  },
  item: {
    flex: 1,
    flexDirection: "row",
    width: "100%",
  },
  image: {
    width: 50,
    height: 50,
  },
  text: {
    width: 50,
  },
});

这个!

const [data, setData] = useState([{ title: "", data: [] }]);

这个!!

setData([
      { title: "popular", data: json1.data.children.slice(0, 5) },
      { title: "controversial", data: json2.data.children.slice(0, 5) },
    ]);

这个!!!

   <SectionList
      sections={data}