gpt4 book ai didi

javascript - nextjs : Warning: Prop `className` did not match. 服务器: "x"客户端: "y"

转载 作者:行者123 更新时间:2023-12-05 03:30:09 29 4
gpt4 key购买 nike

这是我的代码:

export default function Nav() {
const { userLogin } = useUser()
console.log(userLogin)

return (
<nav className={styles.nav}>
{!userLogin ? (
<Link href={"/login"}><a className={`${styles.top}`}></a></Link>
) : (
<Link href={"/profile"}><a className={`${styles.userLogged}`}></a></Link>
)}
</nav>
)
}

这是useUser:

export default function useUser(){
var userLogin = false

const cookies = parseCookies()
if (cookies.token) {
userLogin = true
}

return { userLogin }
}

因此,如果 userLoginfalse,则一切正常。

但是如果 userLogintrue 我得到这个错误:

Warning: Prop `className` did not match. Server: "x" Client: "y"

当我使用 cookie 时出现此错误。

我不想使用next/dynamic。因为 dynamic 在点击时再次重新加载组件。

最佳答案

如果 parseCookies 仅发生在客户端,也就是使用 document 那么 next 将具有来自客户端的不同 HTML,这发生在我的 localStorage 上,因为我正在使用 window.

但是因为您使用的是 cookie,所以您可以从 getInitialProps 的请求参数中获取它们:

App.getInitialProps = async ({ ctx }) => {
const { req } = ctx;

const cookies = parseCookies(req ? req.headers.cookie : document.cookie);

return {
pageProps: { cookies }
};
};

如果您正在使用 nookies,它们与 Next.js 的集成很酷这允许您将 ctx 作为第一个参数传递,如下所示:const cookies = parseCookies(ctx)ctx 将来自 getInitialProps 或 getServerSideProps

参见 https://github.com/maticzav/nookies/blob/c4b1ca461e7b04877d295cb740fa8cbc1db2ad36/packages/nookies/src/index.ts?_pjax=%23js-repo-pjax-container%2C%20div%5Bitemtype%3D%22http%3A%2F%2Fschema.org%2FSoftwareSourceCode%22%5D%20main%2C%20%5Bdata-pjax-container%5D#L15

关于javascript - nextjs : Warning: Prop `className` did not match. 服务器: "x"客户端: "y",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70903659/

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