Next.js React 组件 getInitialProps 不绑定道具

imr*_*rok 7 javascript reactjs next.js

在 Next.js 中,您可以在 React 组件中使用一个生命周期方法,该方法绑定到首次加载时的服务器端渲染。

我尝试使用ZEIT 教程中介绍的这个函数(或者在他们的 Github 上),但是 this.props 似乎没有得到函数返回的 JSON。当我单击组件时,控制台会打印一个空对象。

import React from 'react'
import 'isomorphic-fetch'
export default class extends React.Component {
    static async getInitialProps () {
        const res = await fetch('https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json')
        const data = await res.json()
        return { data }
    }
    print() {
        console.log(this.props);
    }
    render() {
        return <div onClick={this.print.bind(this)}>print props</div>
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

由于我的 _app.js(即NextJS 自定义应用程序)中的问题,我在添加 Redux 时遇到了这个问题(不是 Redux 问题)。当我开始在页面中使用 getInitialProps 时,我的道具在渲染时为空,尽管静态调用中有数据。原因是 pageProps 在我的 _app.js 中传播不正确。

所以在我的情况下,修复正在改变,在自定义 _app.js getInitialProps 中,这个:

return {
  ...pageProps,
  initialReduxState: reduxStore.getState()
}
Run Code Online (Sandbox Code Playgroud)

到:

return {
  pageProps: {...pageProps},
  initialReduxState: reduxStore.getState()
}
Run Code Online (Sandbox Code Playgroud)

.. 所以在 NextJS 文档链接中看到的 render 方法可以将它们连接起来。


Rud*_*udi -1

我尝试了你的代码,它似乎工作正常,控制台显示this.props

结果对象