利用前端React Query整合的NextJS伺服器端渲染
P粉790187507
P粉790187507 2024-03-28 15:53:57
0
2
523

我目前有以下 React 查詢實作:

const { data, isSuccess, isLoading } = useQuery(['myQuery', myParams], async () => {
    return myAjaxCall(myParams);
}, {
    cacheTime: 0
});

我將傳回的結果傳遞給自訂元件:

<Results foundRecords={data}/>

我正在將初始搜尋結果傳遞到我的父頁面元件中,以便搜尋引擎抓取工具能夠在初始頁面載入時看到結果(如果請求是在客戶端發出的- 即使用useQuery( ))。

在這種情況下,將傳遞到元件中的初始搜尋值(透過NextJS 的getServerSideProps())與useQuery() 實作整合的最佳方法是什麼?

從我的頭頂來看,它看起來像:

export async function getServerSideProps(context){
    ...
    return {
       initialData: ....
    }
}

export default function MyPage({initialData}){
    const { data, isSuccess, isLoading } = useQuery(['myQuery', myParams], async () => {
        return myAjaxCall(myParams);
    }, {
        cacheTime: 0
    });

    return (
        <Results foundRecords={initialData || data}/>   
    )
}

P粉790187507
P粉790187507

全部回覆(2)
P粉726133917

為了取得 Google 抓取工具的結果,您需要使用標題和說明中提供的元數據,還需要在 Google 控制台中提交您的網域名稱

export default function Mypage({user}) {
    
      return (
        
          
            
            
            
            My page
            
            //Open Graph meta tags...
          
          Home>
        >) 
 }
    
    
export async function getServerSideProps ({ req }) { 
  const user ={...}
  return {props: {user: user}} 
}
P粉799885311

文件建議將資料放入useQuery的initialData中。然後,您可以繼續使用從 useQuery 傳回的 data

export async function getServerSideProps(context){
    ...
    return {
       initialData: ....
    }
}

export default function MyPage({initialData}){
    const { data, isSuccess, isLoading } = useQuery(['myQuery', myParams], async () => {
        return myAjaxCall(myParams);
    }, {
        cacheTime: 0,
        initialData
    });

    return (
           
    )
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板