显示网络json文件中的SectionList



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

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

下面是样式表的定义:

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

this!

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}

相关内容

  • 没有找到相关文章

最新更新