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

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

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

问题

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

const PostPage: NextPage = () => {
  const [editionMode, setEditionMode] = React.useState(false)

  return (
    <MainLayout>
     {editionMode ? <EditPostForm /> : <Post />}
    </MainLayout>
)
英文:

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:

const PostPage: NextPage = () =&gt; {
  const [editionMode, setEditionMode] = React.useState(false)

  return (
    &lt;MainLayout&gt;
     {editionMode ? &lt;EditPostForm /&gt; : &lt;Post /&gt;}
    &lt;/MainLayout&gt;
)

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.

const PostPage: NextPage = ({ data }) => {
  const [editionMode, setEditionMode] = React.useState(data.editMode);

  return (
    <MainLayout>
      {editionMode ? <EditPostForm /> : <Post />}
    </MainLayout>
  );
};

// This gets called on every request
export async function getServerSideProps() {
  // Pass data to the page via props
  return { props: { data: { editMode: false } } };
}

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.

const PostPage: NextPage = ({ data }) =&gt; {
  const [editionMode, setEditionMode] = React.useState(data.editMode)

  return (
    &lt;MainLayout&gt;
     {editionMode ? &lt;EditPostForm /&gt; : &lt;Post /&gt;}
    &lt;/MainLayout&gt;
);

// This gets called on every request
export async function getServerSideProps() {
  // Pass data to the page via props
  return { props: { data: { editMode: false } } };
}

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:

确定