如何在React Universal中呈现从REST服务接收的数据?(Next.js)

node.js React.js

米亚

2020-03-26

我想使用我的React Universal(与Next.js)应用程序中的REST服务调用接收数据fetch(),然后将结果呈现到JSX中,如下所示:

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

这之所以有意义,是因为对fetch的调用是异步的,并且render()在REST服务的调用完成之前完成。

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

我该如何解决?

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

第3742篇《如何在React Universal中呈现从REST服务接收的数据?(Next.js)》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
斯丁前端 2020.03.26

您可以添加static async getInitialProps () {}以将数据加载到props中,然后再渲染页面组件。

More info here: https://github.com/zeit/next.js/blob/master/readme.md#fetching-data-and-component-lifecycle

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android