由于我喜欢将 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 将在服务器中运行不同时,它们如何具有可比性?
神不在的星期二
相关分类