Next.js:ComponentWillMount 与 getInitialProps

Next.js: ComponentWillMount vs. getInitialProps

我正在为我的 React 应用程序使用 Next.js,因为它具有服务器端呈现。正如我通过日志检查的那样,服务器端的两种方法 ComponentWillMountgetInitialProps 都 运行 。这些方法之间有什么区别吗?

我什么时候应该 运行 进入 ComponentWillMount 什么时候应该 运行 进入 getInitialProps

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

componentWillMount 组件生命周期 方法。

根据documentation

componentWillMount() 在安装发生之前立即被调用。它在render()之前调用,因此在该方法中同步调用setState()不会触发额外的渲染。通常,我们建议改用 constructor()。 避免在此方法中引入任何副作用或订阅。对于这些用例,请改用 componentDidMount()。 这是唯一在服务器呈现时调用的生命周期挂钩。

GetInitialProps

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

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

  3. 只能在页面中使用,不能在组件中使用

ComponentWillMount

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

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

警告

50% 的已接受答案是错误的。这就是为什么。让我把我的答案分成两部分:

第 1 部分:

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

  2. 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

错误,GetInitialProps 在 both serverbrowser(记住 Next.js 的目标是通用 JavaScript)。以下是文档中的内容:

With that, we can fetch data for a given page via a remote data source and pass it as props to our page. We can write our getInitialProps to work on both server and the client. So, Next.js can use it on both client and server.

第 2 部分:

第二部分更准确地回答真题。很明显,OP 在 ComponentDidMountComponentWillMount 之间混淆了。因为在 Next.js 的情况下,比较 GetInitialProps 与 ComponentDidMount 更有意义,因为它们都能够进行异步调用以获取数据,并且它们都允许事后渲染(notComponentWillMount 的情况下可能)。

无论您使用哪一种,都存在一些差异:

GetInitialProps:由Next.js提供,总是被触发,所以要小心。当您将一个组件包裹在另一个组件中时,就会发生这种情况。如果父组件有 GetInitialProps,则永远不会触发子组件的 GetInitialProps。有关详细信息,请参阅 this thread

ComponentDidMount: 是 React 实现,它总是在浏览器上触发。

您可能会问:'so when should I use this or that?'。实际上它非常混乱,同时又非常简单。这是一个经验法则:

  • 当您的组件充当 页面 并且您想将数据作为 Props 提供时,使用 GetInitialProps 获取数据。
  • 在子组件(不是页面)上使用 ComponentDidMount,或者当您想在 Ajax 调用时更新状态。