首页 文章

Next.js React组件getInitialProps不绑定props

提问于
浏览
1

在Next.js中,您可以在React组件中使用绑定到第一次加载时服务器端呈现的生命周期方法 .

我尝试使用the ZEIT tutorial(或者on their 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>
    }
}

3 回答

  • 0

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

    Result object

  • 0

    您可以在getInitialProps方法中进行调用,只需对代码进行少量修改即可

    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 { jsonData: data }
        }
        print() {
            console.log(this.props.jsonData);
        }
        render() {
            return <div onClick={()=> this.print()}>print props</div>
        }
    }
    
  • 0

    我有这个问题是由于我的_app.js(即NextJS Custom App)中的一个问题,我在Redux中添加时引起了问题(不是Redux问题) . 一旦我开始在页面中使用getInitialProps,我的道具在渲染时为空,尽管静态调用中存在数据 . 原因是我的_app.js中pageProps的传播不正确 .

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

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

    至:

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

    ..所以在NextJS doc链接中看到的render方法可以通过它们 .

相关问题