我正在React中对一个API进行axios.get调用。当我第一次运行它时,我得到了我所期望的结果。当我下一次运行它并搜索同样的东西时,我得到的结果比我原来的更多。然后,如果我再次搜索同样的东西,我得到的结果比第二次更多。它一直在旧的结果上添加新的结果,而没有开始一个全新的搜索。如果我搜索不同的关键词,那么我得到的结果既有新的关键词结果,也有我之前搜索的旧结果。
可能有一个简单的解决方法,但我如何让它丢弃旧结果并创建新结果? 我已经尝试创建CancelTokens,但还没有成功.我目前正在将结果放入一个新的数组中,并且当我第一次渲染组件时,我将该数组设置为无,所以我不明白这个问题是如何首先发生的。
谢谢你能提供的任何帮助
async componentDidMount() {
//searches the api for the hashtag that the user entered
newArray.length=0;
newArray=[];
await axios.get(`https://laffy.herokuapp.com/search/${this.props.toSearch}`).then(function(response) {
returnedKeywordSearch = response.data;
}) //if the api call returns an error, ignore it
.catch(function(err) {
return null;
});
//goes through the list of locations sent from the api above and finds the latitude/longitude for each
var count = 0;
while (count < returnedKeywordSearch.length) {
locationToSearch = returnedKeywordSearch[count].location;
if (locationToSearch !== undefined) {
var locationList = await axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${locationToSearch}.json?access_token=pk.eyJ1IjoibGF1bmRyeXNuYWlsIiwiYSI6ImNrODlhem95aDAzNGkzZmw5Z2lhcjIxY2UifQ.Aw4J8uxMSY2h4K9qVJp4lg`)
.catch(function(err) {
return null;
});
if (locationList !== null) {
if (Array.isArray(locationList.data.features) && locationList.data.features.length)
{
locationCoordinates.push(locationList.data.features[0].center);
if (returnedKeywordSearch[count].location!== null && returnedKeywordSearch[count].location!==""
&& locationList.data.features[0].center !== undefined)
{newArray.push({
id: returnedKeywordSearch[count].id,
createdAt: returnedKeywordSearch[count].createdAt,
text: returnedKeywordSearch[count].text,
name: returnedKeywordSearch[count].name,
location: returnedKeywordSearch[count].location,
coordinates: locationList.data.features[0].center
});
}
}
}
}
count++;
}
//tweetSpots is set to null in the initial component state set up
this.setState({tweetSpots: newArray});
this.setState({ done: true}); //sets done to true so that loading animation goes away and map displays
}
好吧,我发现这个问题其实是在Express的服务器端,数据没有被重置。所以,我就关闭这个问题,开一个关于Express的问题。