react-native - React-Native & async 函数:设置条件值
问题描述
我正在尝试为 iconColor 道具返回一个条件值。如果值 isFav 返回 true 我想将 iconColor 设置为红色,否则它应该是白色的。我已经为变量 red 分配了一个十六进制值,而我正在使用的样式库可以识别白色(字符串)。尽管 isFav() 返回 false(我已经记录了值),但 iconColor 始终为红色。你知道为什么会这样吗?
谢谢你的帮助!
async function isFav(title) {
const value = await AsyncStorage.getItem(title)
if (value) {
return true;
} else {
return false;
}
}
function _renderItem({ item }, navigation) {
return (
<TouchableWithoutFeedback onPress={() => navigation.navigate("oneRecipe", {item: item})}>
<View style={styles.recipesItem}>
<CardTextComponent
imageUri={item.image}
title={item.title}
subtitle={`Your Ingredients: ${item.usedIngredientCount}`}
showFavs={true}
iconColor={(async() => isFav()) ? red : "white"}
/>
</View>
</TouchableWithoutFeedback>
);
}
解决方案
为什么不使用状态来代替?
const [isFav, setIsFav] = useState(false);
const _isFav = async ()=> {
const value = await AsyncStorage.getItem(title)
if (value) {
return setIsFav(true);
}
return setIsFav(false);
}
useEffect(()=>{
_isFav()
},[])
const _renderItem = ({ item }, navigation)=> {
return (
<TouchableWithoutFeedback onPress={() => navigation.navigate("oneRecipe", {item: item})}>
<View style={styles.recipesItem}>
<CardTextComponent
imageUri={item.image}
title={item.title}
subtitle={`Your Ingredients: ${item.usedIngredientCount}`}
showFavs={true}
iconColor={ isFav ? "red" : "white"}
/>
</View>
</TouchableWithoutFeedback>
);
}
推荐阅读
- angular - Angular:使用@ContentChildren 让孩子进入另一个组件
- mongodb - 如何使用 mongoDB 比较查询运算符检查 createdAt 日期之间的值?
- c++ - 在字符数组维度分析中构造字符数组
- ios - Alamore 将发布请求转换为服务器日志中的获取请求
- amazon-web-services - 我们可以使用预配置的 AMI 来创建 AWS EMR 集群吗?
- r - 如何根据列中的值扩展数据框
- javascript - VueJS 命名空间的 Vuex 模块 getter 在页面加载时返回不正确的值
- c# - 调用虚拟方法而不是覆盖
- java - 虽然循环给了我一个“
“ 错误 - google-cloud-python - 增加连接池大小