Next.js不会在服务器端渲染布尔状态的默认JSX。

huangapple go评论104阅读模式
英文:

Nextjs does not render server side the default jsx of a boolean state

问题

我有一个用于呈现“Post”的简单nextjs页面。一切都很顺利,nextjs在服务器端呈现完整页面,以获得完美的SEO体验。然而,我想添加一个使用布尔状态的编辑模式:

  1. const PostPage: NextPage = () => {
  2. const [editionMode, setEditionMode] = React.useState(false)
  3. return (
  4. <MainLayout>
  5. {editionMode ? <EditPostForm /> : <Post />}
  6. </MainLayout>
  7. )
英文:

I have a simple nextjs page for the rendering of a Post. Everything run fine and nextjs render the complete page server side for a perfect SEO experience. However I wanted to add an edition mode using a boolean state:

  1. const PostPage: NextPage = () =&gt; {
  2. const [editionMode, setEditionMode] = React.useState(false)
  3. return (
  4. &lt;MainLayout&gt;
  5. {editionMode ? &lt;EditPostForm /&gt; : &lt;Post /&gt;}
  6. &lt;/MainLayout&gt;
  7. )

Sadly with this logic, nextjs doesn't render server side the &lt;Post /&gt;.

So I know I could just remove this condition, always render the &lt;Post /&gt; and put the &lt;EditPostForm /&gt; into a modal or simply add a new endpoint like /posts/:postId/edit, but I wanted to know if there was just a simpler way to handle this case with a simple boolean value so that nextjs still server side render the default one.

答案1

得分: 2

To generate SSR, you should use the getServerSideProps method to provide server-side rendering props.

And your useState's default value should be powered by the props.

  1. const PostPage: NextPage = ({ data }) => {
  2. const [editionMode, setEditionMode] = React.useState(data.editMode);
  3. return (
  4. <MainLayout>
  5. {editionMode ? <EditPostForm /> : <Post />}
  6. </MainLayout>
  7. );
  8. };
  9. // This gets called on every request
  10. export async function getServerSideProps() {
  11. // Pass data to the page via props
  12. return { props: { data: { editMode: false } } };
  13. }

I am curious about how your state becomes true to return the EditionMode component.

英文:

To generate SSR, you should use the getServerSideProps to provide the server side render props.

And your useState's default value should get powered by the props.

  1. const PostPage: NextPage = ({ data }) =&gt; {
  2. const [editionMode, setEditionMode] = React.useState(data.editMode)
  3. return (
  4. &lt;MainLayout&gt;
  5. {editionMode ? &lt;EditPostForm /&gt; : &lt;Post /&gt;}
  6. &lt;/MainLayout&gt;
  7. );
  8. // This gets called on every request
  9. export async function getServerSideProps() {
  10. // Pass data to the page via props
  11. return { props: { data: { editMode: false } } };
  12. }

I am curious about how your state becomes true to return the EditionMode component.

huangapple
  • 本文由 发表于 2023年5月22日 15:11:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76303763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定