getServerSideProps未使用导入更新数据



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()函数,以便在权限更改时重新验证这些值。然而,getServerSideProps中没有重新验证选项,因此根本没有对数据进行重新验证。我以前使用过getInitialProps,但几乎所有人都不鼓励这样做,因为它禁用了ASO。

如何使用getServerSideProps,以便至少重新验证导入的json?

由于其他原因,我最终没有使用json导入,而是使用了fs,但通过在getServerSideProps:中使用动态导入解决了问题

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

另外,不要犯同样的错误,将整个权限数据库传递给每个用户,就像在getStaticProps中使用类似getPermissions的函数将数据传递给页面中的hasPermission函数一样。相反,如果用户有权限,则仅使用getServerSideProps提供数据。换言之,确保从服务器端保留数据。如果需要,你也可以通过个人对页面的权限,比如显示一条消息,说你没有权限。

最新更新