【发布时间】: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