Nextjs:ComponentWillMount与getInitialProps [英] Nextjs: ComponentWillMount vs getInitialProps

查看:235
本文介绍了Nextjs:ComponentWillMount与getInitialProps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的React应用程序使用 next.js ,因为它具有服务器端渲染功能.正如我通过日志检查的那样,方法ComponentWillMountgetInitialProps都在服务器端运行.所以我的问题是:这些方法之间有什么区别吗?我什么时候应该在ComponentWillMount中运行,什么时候应该在getInitialProps中运行.我看不到Next.JS提到了这件事.

I'm using next.js for my React app because it has server side rendering. As I checked by log, both methods ComponentWillMount and getInitialProps both run on server side. So my question is: Are there any differences between those method ? When should I run in ComponentWillMount and when should I run in getInitialProps. I don't see Next.JS mentions about this thing.

推荐答案

GetInitialProps

GetInitialProps

  1. GetInitialProps通常是一个异步函数,对
    服务器上的异步操作,并将数据传递给页面 道具.

  1. GetInitialProps is a usually an async function which is good for
    asynchronous operations at the server and passes data to the page as props.

在nextJs中,它始终在服务器上运行,如果使用链接调用页面,则仅在客户端上调用该页面.

In nextJs it always runs at the server, if the page is called using Link then it is only called at the client side.

它只能用于不在组件中的页面.

It can only be used in pages not in components.

ComponentWillMount

ComponentWillMount

  1. 这是一个生命周期钩子,仅在render方法被调用之前被调用.在其中获取的数据不能作为prop传入.

  1. it is a lifecyle hook it is callled just before the render method is called .Data fetched in it cannot be passed in as a prop.

可以在组件以及页面中调用它.它不是进行异步调用的好地方,因为它不等待异步操作完成.因此,如果它在服务器上运行并且在其中写入了异步操作,那么..将不会完成,并且会在不获取数据的情况下进入客户端.

it can be called in component as well as in pages. it not a good place to make asynchronous call as it dont wait to async operation to complete. so if it runs at server and your async operation is written in it ..will not get completed and it comes to the client without getting data.

这篇关于Nextjs:ComponentWillMount与getInitialProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆