有条件地呈现API中的数据



所以我想有条件地呈现一个项目从我工作的API。例如,如果title={item.title}返回一个空数据,那么应用程序应该将标题渲染为类似字符串的东西。这是代码,提前感谢!

我正在使用的代码:

const getArticles = () => {
axios
.get(
"https://newsapi.org/v2/top-headlines?country=us&apiKey=API-KEY",
{
params: {
category: "technology",
},
}
)
.then((response) => {
setArticles(response.data.articles);
})
.catch(function (error) {
console.log(error);
})
.then(function () {});
};
useEffect(() => {
getArticles();
}, []);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={articles}
renderItem={({ item }) => (
<Artikel
urlToImage={item.urlToImage}
title={item.title}
description={item.description}
author={item.author}
publishedAt={item.publishedAt}
sourceName={item.source.name}
url={item.url}
content={item.content}
/>
)}
keyExtractor={(item) => item.title}
/>
</SafeAreaView>
);
};

这是我使用我已经渲染的数据的卡组件:

<SafeAreaView style={styles.container}>
<Pressable onPress={() => goToDetail(props)}>
<Image
style={styles.image}
on
source={{
uri: props.urlToImage,
}}
/>
</Pressable>
<View style={{ paddingHorizontal: 20, paddingBottom: 10 }}>
<Text style={styles.title}>{props.title}</Text>
<Text style={styles.deskripsi} numberOfLines={3}>
{props.description}
</Text>
<View style={styles.data}>
<Text style={styles.h2}>
source:<Text style={styles.sumber}> {props.sourceName}</Text>
</Text>
<Text style={styles.tanggal}>
{moment(props.publishedAt).format("MMM Do YY")}
</Text>
</View>
</View>
</SafeAreaView>

我喜欢如果数据返回一个空值应用程序会渲染其他东西我手工制作(即字符串)

如果我明白你想要实现什么,使用条件渲染使用三元操作符:

<SafeAreaView style={styles.container}>
<Pressable onPress={() => goToDetail(props)}>
<Image
style={styles.image}
on
source={{
uri: props.urlToImage,
}}
/>
</Pressable>
<View style={{ paddingHorizontal: 20, paddingBottom: 10 }}>
<Text style={styles.title}>{!!props.title ? : props.title : "empty title placeholder"}</Text>
<Text style={styles.deskripsi} numberOfLines={3}>
{props.description}
</Text>
<View style={styles.data}>
<Text style={styles.h2}>
source:<Text style={styles.sumber}> {props.sourceName}</Text>
</Text>
<Text style={styles.tanggal}>
{moment(props.publishedAt).format("MMM Do YY")}
</Text>
</View>
</View>
</SafeAreaView>

最新更新