Javascript 同一页面中API对不同数据的不同请求,React(无重复)
要从API获取不同的数据,我应该使用不同的请求还是一次获取来更改变量?。 我浏览了互联网,答案/建议几乎都是关于PHP的,我对这种语言不是很了解。因此,我在此寻求建议/答案 这是我目前的代码:Javascript 同一页面中API对不同数据的不同请求,React(无重复),javascript,reactjs,api,fetch,Javascript,Reactjs,Api,Fetch,要从API获取不同的数据,我应该使用不同的请求还是一次获取来更改变量?。 我浏览了互联网,答案/建议几乎都是关于PHP的,我对这种语言不是很了解。因此,我在此寻求建议/答案 这是我目前的代码: //fetching movie fetchMovie = (name) =>{ const API = '&api_key=72049b7019c79f226fad8eec6e1ee889'; let movieAPI = ''; //if the lengt
//fetching movie
fetchMovie = (name) =>{
const API = '&api_key=72049b7019c79f226fad8eec6e1ee889';
let movieAPI = '';
//if the length of the movies is equal to zero fetch default search
if( this.state.movies.length === 0 ){
movieAPI = "https://api.themoviedb.org/3/discover/movie?api_key=72049b7019c79f226fad8eec6e1ee889&sort_by=popularity.desc&page=1";
}else{
//search the movie name
movieAPI = "https://api.themoviedb.org/3/search/movie?page=1&query=" + name + API;
}
//make request
const req = new Request(movieAPI, {
method: 'GET',
cache: 'default'
});
fetch(req).then(response =>{
return response.json();
}).then(data =>{
//if data fetched result is greater than 0
if(data.results.length > 0){
this.setState({
movies: data.results
});
}
}).catch(err => {
console.log("ERROR: " + err);
})
}
现在我想解释的是:
正如您从上面的代码中看到的,我只能按数据或名称执行默认请求。现在,如果我想获取不同的查询,我应该为每个查询编写不同的代码,还是重复使用代码,以便:
movieAPI = "https://api.themoviedb.org/3/"+ variable +"/movie?api_key=72049b7019c79f226fad8eec6e1ee889&date="+ date +"&name=" +name + "&otherQuery=" + query ;
这实际上取决于你的应用程序将如何处理这些数据 我建议您为应用程序获取的每种数据类型创建多个函数,如下所示:
function fetchMovieByName(name){ ... }
function fetchMovieListByDate(beginDate, endDate, sort, page){ ... }
function fetchPopularMovieList(sort, page){ ... }
function fetchTopRatedMovieList(sort, page){ ... }
这将更清晰,更容易理解您的代码
如果你想减少请求量,你可以获取一个列表,然后将其存储,并在客户端进行搜索/筛选等。这实际上取决于你的应用程序将如何处理这些数据 我建议您为应用程序获取的每种数据类型创建多个函数,如下所示:
function fetchMovieByName(name){ ... }
function fetchMovieListByDate(beginDate, endDate, sort, page){ ... }
function fetchPopularMovieList(sort, page){ ... }
function fetchTopRatedMovieList(sort, page){ ... }
这将更清晰,更容易理解您的代码
如果你想做更少的请求,你可以获取一个列表,然后存储它,并在客户端进行搜索/过滤等