英文:
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 = () => {
const [editionMode, setEditionMode] = React.useState(false)
return (
<MainLayout>
{editionMode ? <EditPostForm /> : <Post />}
</MainLayout>
)
Sadly with this logic, nextjs doesn't render server side the <Post />
.
So I know I could just remove this condition, always render the <Post />
and put the <EditPostForm />
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 }) => {
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论