簡體   English   中英

getServerSideProps 不使用導入更新數據

[英]getServerSideProps is not updating data with import

我在 NextJS 中的getServerSideProps遇到問題,沒有在頁面加載時更新值。 從導入的 json 文件的數據調用時,它似乎與使用getStaticProps具有相同的效果。

這是適用的代碼:

/update/[...id].js

import { hasPermission, getPermissions } from '../../lib/permissions'
...
//in the page function I use the ternary to check permission of the user
{ (hasPermission(session.user.email, `${params.id[0]}-edit`, permissions)) ? <HasPerm /> : <NoPerm /> }
...
export async function getServerSideProps(context) {
  const params = context.query
  const permissions = getPermissions()
  return {
    props: { params, permissions }
  }
}

/lib/permissions.js

import permissions from '../db/users.json'

export function hasPermission(username, group, perm = false) {
  if (!perm)
    perm = permissions

  if (username in perm && perm[username].groups.includes(group)) {
    return true
  }
  if (perm.all.groups.includes(group)) {
    return true
  }
  return false
}

export function getPermissions() {
  return permissions
}

對於一開始就可以理解的 SSR 頁面,我將權限傳遞給getStaticProps中的頁面,並將這些值傳遞到這些頁面中的我的hasPermission() function 中,以便在權限更改時重新驗證它們。 但是getServerSideProps中沒有重新驗證選項,因此根本不會重新驗證數據。 我之前使用過getInitialProps ,但幾乎每個人都不鼓勵這樣做,因為它禁用了 ASO。

如何使用getServerSideProps以使我導入的 json 至少重新驗證? 謝謝

我最終沒有使用 json 導入並使用fs代替其他原因,但通過在getServerSideProps中使用動態導入解決了這個問題:

export async function getServerSideProps(context) {
  const permissions = await import('../db/users.json')
}

也不要犯同樣的錯誤,將整個權限數據庫傳遞給每個用戶,就像使用getStaticProps中的getPermissions之類的 function 將數據獲取到頁面中的hasPermission function 一樣。 相反,只有在用戶有權限的情況下才使用getServerSideProps提供數據。 換句話說,確保您從服務器端保留數據。 然后,如果需要,您還可以將個人的權限傳遞給頁面,例如顯示一條消息說您沒有權限。

暫無
暫無

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

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