javascript - 检查用户输入是否已经在收藏夹数组中无法正常工作
问题描述
我正在尝试构建一个天气应用程序,但是这两天出了点问题。
我有两个组件,一个称为主页,另一个称为收藏夹,我想做的是通过输入城市将其添加到收藏夹中并将其删除。
我遇到的错误很简单,但我想不通->
当用户进入一个城市时,该功能需要检查它是否已经在收藏夹中,如果它是按钮上的文本应该更改为“从收藏夹中删除”,当它不在收藏夹中时,文本需要保持“添加到收藏夹”它仅在第一次运行良好这意味着如果例如我输入东京并按添加到收藏夹它会正确添加它并且如果我再次编写它仍然可以工作但是当我进入一个新城市时,例如,纽约我将无法再次编辑东京,但我将能够编辑纽约,这意味着我只能删除我写的最后一件事。
为了把事情说清楚——
我是用户,我在输入中输入东京,按添加到收藏夹,它将被添加并且文本将从收藏夹中删除,纽约也是如此,但是当我再次写东京时,文本将保留添加到收藏夹中应该从收藏夹中删除。
检查我的收藏夹中是否已经有城市的功能---
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')
}
}
想要你们的帮助。
解决方案
推荐阅读
- gmail-api - 如何过滤 Google Api 收件箱以仅阅读主要消息?
- node.js - MongoDB 和 Mongoose - UpdateMany,为特定文档分配特定值
- python - 可以创建不同数量的框架/选项卡对象并将每个对象绑定到一个名称吗?
- typescript - 缺少调用签名 - Array.prototype.map()
- javascript - 使用字符串数组替换字符串中的出现
- windows - 如何检测 Delpi 代码在 DLL 中运行?
- javascript - 如何检查 Javascript/jQuery/Ajax 环境设置?
- ruby - 如何从 Terraform 中的外部数据源访问 JSON?
- macos - 我成功地使用 curl 代码将文本下载到 Visual Studio 代码中。有没有办法重定向它并将其保存为文本文件?
- c - 如何运行此文本文件并使用 strtok() 提取数字并将数字存储在不同的文件中?