首页 > 解决方案 > 我可以将 getInitialProps 代码移动到 componentDidMount 吗?

问题描述

我想将静态 getInitialProps 中的代码移动到 componentDidMount。但是,getInitialProps 中有两个参数(组件,ctx),我应该全部使用它们。我只想知道我是否可以移动代码。谢谢!

不知道..

// Current
class extends App {
  public static async getInitialProps({Component, ctx}) {
     // Do Something with two parameters
  }
  .
  .
  .
}

// What I want to do
class extends App {
  public componentDidMount() {
    // Do the same thing
  }
  .
  .
  .
}

标签: reactjsnext.jsserver-side-rendering

解决方案


getInitialProps在服务器端和客户端都可以使用,而componentDidMount仅适用于客户端。因此,您不能在内部使用它componentDidMount

如果您想使用getInitialProps在 componentDidMount 中获取的数据,您可以从中返回数据getInitialProps并将其用作prop.

class extends App{
  static async getInitialProps({ Component, ctx }) {
    //do some data fetching
    return { data };
  }

  constructor() {
    super();
    this.state = {};
  }

  componentDidMount() {
    console.log(this.props.data)
  } 

}


推荐阅读