首页 > 解决方案 > 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>
    );
  }

标签: react-nativeasync-awaitcallbackconditional-statements

解决方案


为什么不使用状态来代替?

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

推荐阅读