首页 > 解决方案 > 检查用户输入是否已经在收藏夹数组中无法正常工作

问题描述

我正在尝试构建一个天气应用程序,但是这两天出了点问题。

我有两个组件,一个称为主页,另一个称为收藏夹,我想做的是通过输入城市将其添加到收藏夹中并将其删除。

我遇到的错误很简单,但我想不通->

当用户进入一个城市时,该功能需要检查它是否已经在收藏夹中,如果它是按钮上的文本应该更改为“从收藏夹中删除”,当它不在收藏夹中时,文本需要保持“添加到收藏夹”它仅在第一次运行良好这意味着如果例如我输入东京并按添加到收藏夹它会正确添加它并且如果我再次编写它仍然可以工作但是当我进入一个新城市时,例如,纽约我将无法再次编辑东京,但我将能够编辑纽约,这意味着我只能删除我写的最后一件事。

为了把事情说清楚——

我是用户,我在输入中输入东京,按添加到收藏夹,它将被添加并且文本将从收藏夹中删除,纽约也是如此,但是当我再次写东京时,文本将保留添加到收藏夹中应该从收藏夹中删除。

检查我的收藏夹中是否已经有城市的功能---

    useEffect(()=>{
    for(let i=0;i<allFavorite.length;i++){
        if(userInput == allFavorite[i].name){
            setButtonText('Remove from favorites') 
            
        }else{
            setButtonText('Add to favorites')}
        }
    })

The function that checks if the city name is valid and removes the city from favorites -

    const ValidLocation=new RegExp("^[a-zA-Z_ ]+$");
// if(!RegEx.test(valType))
let cityKey;
let addToFavAndRemove=()=>{
if(buttonText=='Add to favorites'){
    if(ValidLocation.test(userInput) && userInput.length>3){
        fetch(`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=lyCvf3AfRlFcehI7egWl43dndCx5vyLp&q=${userInput}`, {
        })
        .then((response) => {
            return response.json();
        })
        .then((jsonObject) => {
            
            // setCityKey(jsonObject[0].Key)
            cityKey=jsonObject[0].Key
            return jsonObject;
        })
        setTimeout(()=>{
            WeatherCondition()
            console.log(cityKey)
        },900)
    }
    else{
        alert('Invalid location')

    }
}

else{
        allFavorite.map((item,index)=>{   
    let updatedFavorite=allFavorite.filter((item,i)=>(index!=i))
    setAllFavorite(updatedFavorite)
    })
        console.log('d')
    }
}

想要你们的帮助。

标签: javascriptreactjs

解决方案


推荐阅读