Next.js:ComponentWillMount 与 getInitialProps [英] Next.js: ComponentWillMount vs. getInitialProps

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

问题描述

我正在将 Next.js 用于我的 React 应用程序,因为它具有服务器端渲染.当我通过日志检查时,ComponentWillMountgetInitialProps 两种方法都在服务器端运行.这些方法之间有什么区别吗?

I'm using Next.js for my React application because it has server side rendering. As I checked by log, both methods ComponentWillMount and getInitialProps both run on the server side. Are there any differences between those methods?

什么时候应该在 ComponentWillMount 中运行,什么时候应该在 getInitialProps 中运行?

When should I run in ComponentWillMount and when should I run in getInitialProps?

我没有看到 Next.js 提到这件事.

I don't see Next.js mentions about this thing.

推荐答案

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.

在 Next.js 中,它总是在服务器端运行,如果页面是使用 Link 调用的,那么它只会在客户端调用.

In Next.js 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

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

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

它既可以在组件中调用,也可以在页面中调用.这不是进行异步调用的好地方,因为它不会等待异步操作完成.因此,如果它在服务器上运行并且您的异步操作写入其中,则它不会完成并且在没有获取数据的情况下到达客户端.

It can be called in a component as well as in pages. It is not a good place to make asynchronous calls as it doesn't wait for the async operation to complete. So if it runs at the server and your async operation is written in it, it will not get completed and it comes to the client without getting data.

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

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