Nextjs getInitialProps 阻止了客户端的页面渲染?

由于我喜欢将 SSR 添加到我即将进行的项目中以改进 SEO,因此我想尝试下一个。我想要的是只对初始页面使用 SSR,站点中的其余导航将是客户端渲染。我认为 getInitialProps 在这种情况下最适合,因此文档。


据我了解,getInitialProps 在服务器中运行以进行初始页面渲染,并在使用 next/link 导航时在浏览器中运行。我发现的问题是 getInitialProps 似乎阻止了页面渲染。(即 getInitialProps 完成后页面更改/渲染)


import axios from 'axios'


function Posts(props) {

  return (

    <div>

      <div>Posts:</div>

      <div>

        {JSON.stringify(props)}

      </div>

    </div>

  )

}


Posts.getInitialProps = async (context) => {

  const response = await axios.get('https://jsonplaceholder.typicode.com/posts');

  // Wait longer to see the effect

  // await (new Promise((resolve) => {

  //   setTimeout(resolve, 5000)

  // }))

  return {

    props: {

      posts: response.data

    }

  }

}


export default Posts;

我怎么能像在纯 React 中那样,先渲染 jsx,然后填充道具?(执行 JSON.stringify(props) 一开始可能会被忽略)


此外,在接下来的 9.3 中,团队引入了 getServerSideProps,推荐使用它而不是 getInitialProps。当它们与 getServerSideProps 将在服务器中运行不同时,它们如何具有可比性?


蝴蝶刀刀
浏览 232回答 1
1回答

神不在的星期二

根据您的评论,您希望在初始页面加载时在服务器上进行提取。但是,如果在页面之间导航,您不想在等待getInitialProps返回时阻止渲染。一种解决方案是检查您是否在服务器上,然后在getInitialProps. 如果在客户端上,请不要进行获取getInitialProps,而是useEffect在您的渲染方法中使用获取。import {useEffect} from 'react'import axios from 'axios'const isServer = () => typeof window === 'undefined'const getPosts = () => {&nbsp; return axios.get('https://jsonplaceholder.typicode.com/posts')&nbsp; &nbsp; .then(response => response.data)}function Posts({posts}) {&nbsp; const [renderPosts, setRenderPosts] = useState(posts)&nbsp; useEffect(() => {&nbsp; &nbsp; if(posts === null) {&nbsp; &nbsp; &nbsp; getPosts()&nbsp; &nbsp; &nbsp; &nbsp; .then(setRenderPosts)&nbsp; &nbsp; }&nbsp; }, [])&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <div>Posts:</div>&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; {JSON.stringify(renderPosts)}&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; )}Posts.getInitialProps = async (context) => {&nbsp; if(isServer()) {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; posts: await getPosts(),&nbsp; &nbsp; }&nbsp; }&nbsp; else {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; posts: null,&nbsp; &nbsp; }&nbsp; }}export default Posts顺便说一句,您可能很想在getServerSideProps这里使用它,因为它仅在服务器上渲染时才被调用。但是,当getServerSideProps呈现使用的页面时,它实际上会调用服务器以从 获取数据getServerSideProps,即使您正在使用 导航next/link。来自Next.js 9.3 博客文章:当使用 next/link 在页面之间导航而不是在浏览器中执行 getServerSideProps 时,Next.js 将对服务器进行获取,这将返回调用 getServerSideProps 的结果。这仍然会导致您想要避免的阻塞问题。最后一点,这可能不是一个惯用的解决方案。可能有一个更“标准”的解决方案。我只是找不到一个。您可能还可以在页面组件周围使用包装器,它可以以更一致的方式完成所有这些工作。如果你经常使用这种模式,我会推荐它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript