2016-11-30 98 views
0

在Next.js中,您可以在您的React組件中使用綁定到第一次加載時的服務器端渲染的生命週期方法。Next.js React組件getInitialProps不綁定道具

我試圖使用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> 
    } 
} 
+0

你必須在/ pages組件中得到它。否則getInitialProps不會被調用。你是定義一個頁面還是一個組件? – elmasse

回答

0

getInitialProps,如果我沒有記錯是React.createClass功能和React.Component不存在。

如果你想獲取一些數據,然後在componentDidMount(不推薦使用WillMount)。您的渲染函數應該意識到初始渲染不會獲取提取的數據。您也可以將提取級別提高一級,並將組件設置爲「dumber」,並只接收一些特定的道具以顯示(推薦)。

另請注意,您只需要在應用程序中導入一次性異構獲取一次,以便您可以在入口點文件或其附近執行此操作。

import React, { Component } from 'react' 

export default class extends Component { 
    constructor() { 
     super(); 
     this.state = {}; 
    } 
    async componentDidMount() { 
     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(); 
     this.setState({ data }); 
    } 
    render() { 
     const data = this.state.data; 
     if (!data) { 
      return <div>Loading...</div>; 
     } 
     return <div>{JSON.stringify(data)}</div> 
    } 
} 
+0

在[next.js'Github]提供的示例(https://github.com/zeit/next.js#component-lifecycle)中,組件是這樣定義的:'export default class extends React.Component' – OhmWang

+0

啊好吧,我猜'getInitialProps'是'next.js'的一種特殊方法。 「頂層組件可以定義getInitialProps,以阻止路由的加載(無論是在服務器渲染還是延遲加載時)」 –

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