【问题标题】:Next.js React component getInitialProps doesn't bind propsNext.js React 组件 getInitialProps 不绑定道具
【发布时间】:2017-04-14 20:34:32
【问题描述】:

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

【问题讨论】:

  • 您必须在 /pages 组件中获取它。否则不会调用 getInitialProps。您是在定义页面还是组件?

标签: javascript reactjs next.js


【解决方案1】:

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

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

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

到:

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

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

【讨论】:

  • 这应该是公认的答案。对我来说,这是一个救命稻草,我自己永远不会解决这个问题。我知道这已经一年了,但如果可能的话,您或其他人能否更详细地解释为什么会出现此问题以及修复的具体工作原理?
【解决方案2】:

您可以像这样在 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>
    }
}

【讨论】:

  • 我得到undefined :( 在控制台和Access to fetch at 'https://en.wikipedia.org/w/api.php?action=query&amp;titles=Main%20Page&amp;prop=revisions&amp;rvprop=content&amp;format=json' from origin 'http://localhost:7777' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
  • @ChanceSmith 这与reactnextjs 无关。这与cors 政策有关。你应该谷歌它是什么,这样你就可以更好地理解
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-19
    • 2019-10-12
    • 2021-05-05
    • 2018-08-24
    • 2020-04-24
    • 2019-10-04
    • 2021-03-31
    • 2020-09-19
    相关资源
    最近更新 更多