【发布时间】:2021-07-27 06:54:06
【问题描述】:
我从一个记录国家名称和人口的 API 中获取。我在搜索平面列表中有国家名称。我的目标是根据人口在平面列表上的国家名称旁边显示一个小圆圈。如果人口在100M以上,圆圈为红色,如果在10M以上小于50M,圆圈为橙色,如果小于10M,圆圈为绿色。条件渲染是正确的方法吗?或者我可以换一种方式吗?
我当前的代码如下:
const [filteredData, setFilteredData] = useState<any>();
const [masterData, setMasterData] = useState([]);
const [filteredPopulationData, setFilteredPopulationData] = useState<any>();
const [masterPopulationData, setMasterPopulationData] = useState([]);
useEffect(() => {
fetchData();
return () => {};
}, []);
const fetchData = () => {
const apiURL =
"https://raw.githubusercontent.com/samayo/country-json/master/src/country-by-population.json";
fetch(apiURL)
.then((response) => response.json())
.then((responseJson) => {
setFilteredStateData(responseJson);
setMasterStateData(responseJson);
})
.catch((error) => {
console.error(error);
});
};
const SearchFilter = (text) => {
if (text) {
const newData = filteredData.filter((item) => {
const itemData = item.country;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setFilteredData(newData);
setSearch(text);
} else {
setFilteredData(masterData);
setSearch(text);
}
if (text) {
const newPopulationData = filteredPopulationData.filter((item) => {
const itemPopulationData = item.population;
const textPopulationData = text.toUpperCase();
return itemPopulationData.indexOf(textPopulationData) > -1;
});
setFilteredPopulationData(newPopulationData);
setSearch(text);
} else {
setFilteredPopulationData(masterPopulationData);
setSearch(text);
}
const renderExtraItem = ({ item }) => {
if ((item.population < 10000000)) {
return (
<View
style={{
width: 10,
height: 10,
borderRadius: 20,
backgroundColor: "green",
}}
/>
);
} if ((item.population >= 10000000 && item.population < 50000000 )) {
return (
<View
style={{
width: 10,
height: 10,
borderRadius: 20,
backgroundColor: "orange",
}}
/>
);
} if ((item.population >= 100000000)) {
return (
<View
style={{
width: 10,
height: 10,
borderRadius: 20,
backgroundColor: "red",
}}
/>
);
}
};
const ItemView = ({ item }) => {
return (
<RectButton
onPress={() => navigate("LocationDataScreen", { name: item.country })}
>
<Text style={[styles.itemStyle, { textTransform: "capitalize" }]}>
{item.id}
{item.country.toUpperCase()}
</Text>
{renderExtraItem(item)}
</RectButton>
);
};
const ItemSeparatorView = () => {
return (
<View
style={{
height: 1.5,
width: "90%",
marginLeft: 35,
backgroundColor: "#f3f2f8",
}}
/>
);
};
return (
<FlatList
data={filteredData}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={ItemSeparatorView}
renderItem={ItemView}
style={styles.listcontainer}
/>
)
【问题讨论】:
标签: json typescript react-native react-native-flatlist country-json