如何使用自定义搜索引擎API对项目进行分页



我正在ReactJs应用程序中从Google自定义搜索引擎API获取数据。我知道这个API只返回前100个结果,每个页面被分成10个结果。

我的变量resultData.items返回一个包含10个项目的数组,其中包含URL、标题、代码段和其他属性。

这就是我的变量resultData.queries返回的值。查看有一个名为nextPage:的属性

{
"request": [
{
"title": "Google Custom Search - google",
"totalResults": "48240000000",
"searchTerms": "google",
"count": 10,
"startIndex": 1,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"safe": "off",
"cx": "c5e7e9c901dcfe0b0"
}
],
"nextPage": [
{
"title": "Google Custom Search - google",
"totalResults": "48240000000",
"searchTerms": "google",
"count": 10,
"startIndex": 11,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"safe": "off",
"cx": "c5e7e9c901dcfe0b0"
}
]
} 

这就是我存储数据的方式:

const Search = () => {    

const [searchText, setSearchText] = useState('');
const [resultData, setResultData] = useState({});
const [loading, setIsLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(5);


function searchInGoogle(e){

const BASE_URL = `https://customsearch.googleapis.com/customsearch/v1`
const API_KEY = process.env.REACT_APP_SEARCH_KEY;
const SEARCH_ENGINE_KEY = process.env.REACT_APP_SEARCH_ENGINE_KEY;    
var apiCall = `${BASE_URL}?key=${API_KEY}&cx=${SEARCH_ENGINE_KEY}&q=${searchText}`
axios.get(apiCall).then(function (response){
setIsLoading(true)
console.log(response.data)
setResultData(response.data)
setIsLoading(false)

}).catch(function(error){
console.log(error);
setIsLoading(false)
})

}
const handleInputChange = (e) => {
setSearchText(e.target.value)

}
const handleNextPage = (e) => {
setCurrentPage(currentPage + 1)
}
const handlePrevPage = (e) => {
setCurrentPage(currentPage - 1)
if(currentPage <= 0){
document.getElementById('prevPage').hidden = true
} else {
document.getElementById('prevPage').hidden = false
}
}
console.log(resultData.items)

const items = resultData.items?.map((item)=>{
return <Item key={item.id} title={item.title} description={item.snippet} url={item.formattedUrl}/>      

}) ?? [] // return an empty array in case the result is undefined

const searchInfo = resultData.searchInformation ? <p>About {resultData.searchInformation.formattedTotalResults} results ({resultData.searchInformation.formattedSearchTime} seconds)</p> : <p></p>

const lastItemIndex = currentPage * itemsPerPage;
const firstItemIndex = lastItemIndex - itemsPerPage;
const totalPages = parseInt(searchInfo.formattedTotalResults) / itemsPerPage;
console.log(totalPages)
return (
<div className='searchPage'>

<Searchbar handleInputChange={handleInputChange} searchInGoogle={searchInGoogle} /> 
<div>
{ (resultData.searchInformation && Object.keys(resultData.searchInformation)) !== 0 ? <>
{searchInfo}
</> : <p></p>  
}
{
(resultData.items && Object.keys(resultData.items)) !== 0 ? <>
{items}
</> : <><p>No results</p></>
}
</div>
<div className='pages'>
<div className='pagination' id='prevPage'><button onClick={handlePrevPage}>Previous</button></div>
<div className='pagination'>{currentPage}</div>
<div className='pagination'><button onClick={handleNextPage}>Next</button></div>
</div>

</div>
)
}
export default Search

我知道这个API在其JSON中有属性nextPagepreviousPage,但我不知道如何访问它们,以及如何将它们与我的逻辑联系起来,并在不同的页面中显示不同的项目,但始终显示相同数量的项目。previousPage没有出现在对象中,因为它是结果的第一页。知道如何在reactjs中使用这个API实现分页吗?

Google一次最多返回10个结果。如果你看看";下一页";对象,您会注意到一个startIndex参数,该参数设置为11。此参数指示将在下一页的请求中返回的第一个文档的索引。您可以通过添加"amp;start=">请求url中的参数。

例如,假设您想要第二页的结果。nextPage对象表示第二页中的第一个文档的索引为11。因此,您对第二个页面的查询应该是这样的(假设您使用的是自定义JSON搜索api(:

"https://www.googleapis.com/customsearch/v1?key={yourKey}&cx={yourSearchEngineId}?q={yourQuery}&start=11

这将返回结果的第二页。类似地,对于其余页面,只需在开始参数的值上加10即可。

希望这能有所帮助!

最新更新