簡體   English   中英

如何最好地將分頁添加到 Reactjs 中的搜索結果查詢?

[英]How best to add pagination to a search result query in Reactjs?

我有一個 MERN 堆棧應用程序,我在 Nodejs 中編寫了搜索查詢和分頁,我在 Reactjs 中實現了分頁部分,並且也想實現搜索查詢。 它正在工作,但沒有分頁。 我想如果搜索結果超過 20 個結果,我只想讓它變成兩頁。 我可以每頁做 12 個搜索結果。 有沒有辦法做到這一點? 我可以在單個 URL 中同時添加搜索和分頁查詢嗎? 這是我的nodejs代碼:

const DEFAULT_PAGE_NUMBER = 1
const DEFAULT_PAGE_LIMIT = 12;


const getPagination =(query) =>{
const page = Math.abs(query.page) || DEFAULT_PAGE_NUMBER;
const limit = Math.abs(query.limit) || DEFAULT_PAGE_LIMIT;

const skip = (page -1) * limit


return {
    skip,
    limit
};

};


const getAllPosts = async (req, res) =>{
      const {skip, limit} = getPagination(req.query);
       const {searches} = req.query;

  if(searches){
       posts = await Post.find({title: {$regex: searches.toString(), "$options": "i"}}).populate('username', 'username').sort({createdAt:-1})
       .skip(skip)
       .limit(limit)  
           
   }
 }

現在,在 Reactjs 中,我為分頁查詢做了這樣的事情:

useEffect(()=>{
 try{
    const response = await axios.get(`/posts/?page=${path}`);
 }catch(err){
 
  }


}, [path]);

這適用於分頁,每頁顯示 12 個帖子。

現在,在 Reactjs 中,我為搜索查詢做了這樣的事情:

useEffect(()=>{
 try{
    const response = await axios.get(`/posts/?searches=${path}`);
 }catch(err){
 
  }


}, [path])

現在,這行得通。 它根據用戶輸入的搜索詞獲取帖子。 問題是結果可能比我在頁面中想要的要多。 有沒有一種方法可以將我寫的分頁查詢也集成到其中,以便當搜索結果超過 12 時,其他帖子將在下一頁上被調用?

我通過在正文中傳遞搜索參數和查詢中的分頁來解決這個問題。 這解決了我的問題。 查看示例代碼

  const {skip, limit} = getPagination(req.query);//pagination
  const search = req.body.search;//search 
 if(search){
    posts = await Post.find({title: {$regex: search.toString(), "$options": "i"}}).populate('username', 'username').sort({createdAt:-1})
       .skip(skip)
       .limit(limit)  
}
else{
  fetch the entire posts if there is no search parameter.
   }

數據表插件提供了非常好的開箱即用的分頁

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM