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

JavaScript React.js

泡芙小胖

2020-03-23

在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>
    }
}

第3134篇《Next.js React组件getInitialProps不绑定道具》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
飞云斯丁GO 2020.03.23

我尝试了您的代码,它似乎正常运行,控制台显示this.props

结果对象

斯丁 2020.03.23

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

因此,在我的情况下,此修复程序正在自定义_app.js getInitialProps中更改:

return {
  ...pageProps,
  initialReduxState: reduxStore.getState()
}

至:

return {
  pageProps: {...pageProps},
  initialReduxState: reduxStore.getState()
}

..因此,如NextJS doc链接中所示的render方法可以将它们连接起来。

问题类别

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