gpt4 book ai didi

reactjs - 如何使用 getStaticProps 重定向?

转载 作者:行者123 更新时间:2023-12-04 12:34:57 28 4
gpt4 key购买 nike

我有一个具有简单用户身份验证的 nextjs 应用程序。这意味着我不希望注销的用户访问一些 protected 路由。该应用程序在开发版本中成功编译并按预期工作。但是当我使用 next build ,我收到一条错误消息 -Error occurred prerendering page "/createNewAdditionalInfo". Read more: https://err.sh/next.js/prerender-error Error: 'redirect' can not be returned from getStaticProps during prerendering (/createNewAdditionalInfo) .
这是代码 -

export async function getStaticProps(ctx) {
let userObject;
let id;
const cookie = parseCookies(ctx);
if (cookie.auth) {
userObject = JSON.parse(cookie.auth);
id = userObject.id;
}
if (!id) {
return {
redirect: {
permanent: false,
destination: '/',
},
};
}

return {
props: {},
};
}

最佳答案

从 nextJS 中的 getStaticProps 重定向

export async function getStaticProps({ params }) {
const db = await getDB()

//get id from url
const id = params.postId

//find post in db
const post = await db().collection("posts").findOne({ _id: id })


// The Redirect Happens HERE
//if no post was found - go to Home page
if (!post) {
return {
redirect: {
destination: "/",
},
}
}

return {
props: {
post: JSON.stringify(post),
},
}
}


export async function getStaticPaths() {
return {
paths: [],
fallback: true,
}
}

关于reactjs - 如何使用 getStaticProps 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65709378/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com