getInitialProps永远不会被调用……我在做什么错?

reactjs React.js

伽罗

2020-03-23

我是React和Next.js的新手,请多多包涵。但是我花了三个小时进行搜索,因此无法终生弄清自己在这里做错了什么。

this.props.test 即使看起来应该输出“ test”,也不会输出任何东西。

就像getInitialProps从来没有调用过。

class Example extends React.Component {

  static async getInitialProps() {
    return {
      test: 'test'
    }
  }

  render() {
    return (
      <h1>Hi {this.props.test}</h1>
    )
 } 

}

第2694篇《getInitialProps永远不会被调用……我在做什么错?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
小胖Gil 2020.03.23

因为getInitialProps仅适用于Next.js中的Pages,所以子组件的正确方法是componentDidMount使用setState而不是props

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android