2017-05-04 38 views
3

我想用fetch()通过在我的阵营通用(含Next.js)应用REST服务调用来接收数据,然后将结果呈现到JSX是这样的:如何呈现从React Universal中的REST服务接收到的数据? (Next.js)

class VideoPage extends Component { 
    componentWillMount() { 
    console.log('componentWillMount'); 

    fetch(path, { 
     method: 'get', 
    }) 
     .then(response => 
     response.json().then(data => { 
      this.setState({ 
      video: data, 
      }); 
      console.log('received'); 
     }) 
    ); 
    } 

    render() { 
    console.log('render'); 
    console.log(this.state); 
    if (this.state && this.state.video) { 
     return (
     <div> 
      {this.state.video.title} 
     </div> 
    ); 
    } 
    } 
} 

export default VideoPage; 

不幸的是,输出是这样的:

componentWillMount 
render 
null 
received 

这有一定道理,因为获取呼叫和异步调用REST服务之前render()结束已完成。

在客户端应用程序中,这是没有问题的,因为状态更改会调用render(),然后更新视图,但是在通用应用程序中,特别是在客户端关闭JavaScript的情况下,这是不可能的。

我该如何解决这个问题?

有没有办法同步调用服务器或延迟render()

回答

1

为了得到它的工作,我必须做3两件事:

  • 更换componentWillMountgetInitialProps()方法
  • 结合fetchawait并返回数据
  • 使用this.props代替this.state

代码现在看起来是这样的:

static async getInitialProps({ req }) { 
    const path = 'http://path/to/my/service'; 
    const res = await fetch(path); 
    const json = await res.json(); 
    return { video: json }; 
} 

然后,在render()我可以通过this.props.video访问数据,例如:

render() { 
    return (
    <div>{this.props.video.title}</div> 
); 
} 
相关问题