在 Next.js 中,您可以在 React 组件中使用一个生命周期方法,该方法在首次加载时绑定(bind)到服务器端渲染。
我尝试使用 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>
}
}
最佳答案
我遇到这个问题是因为我在添加 Redux 时导致我的 _app.js(即 NextJS Custom App)出现问题(不是 Redux 问题)。当我开始在页面中使用 getInitialProps 时,我的 Prop 在渲染时是空的,尽管静态调用中有数据。原因是我的 _app.js 中 pageProps 的传播不正确。
所以在我的例子中,修复正在改变,在自定义 _app.js getInitialProps 中,这个:
return {
...pageProps,
initialReduxState: reduxStore.getState()
}
到:
return {
pageProps: {...pageProps},
initialReduxState: reduxStore.getState()
}
.. 所以在 NextJS 文档链接中看到的渲染方法可以连接它们。
关于javascript - Next.js React 组件 getInitialProps 不绑定(bind) Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40889738/