简体   繁体   English

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

[英]How to render data received from a REST service in React Universal? (Next.js)

I want to receive data via a REST service call in my React Universal (with Next.js) app using fetch() and then render the result into JSX like this: 我希望通过使用fetch()在我的React Universal(使用Next.js)应用程序中通过REST服务调用接收数据,然后将结果呈现为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;

Unfortunately, the output is this: 不幸的是,输出是这样的:

componentWillMount
render
null
received

Which does make sense because the call to fetch is asynchronously and render() finishes before the call to the REST service has finished. 这有意义,因为对fetch的调用是异步的, render()在调用REST服务之前完成。

In a client-side app this would be no problem because a change of state would call render() which then updates the view, but in a universal app, especially with JavaScript turned off on the client, this is not possible. 在客户端应用程序中,这没有问题,因为更改状态会调用render()然后更新视图,但在通用应用程序中,尤其是在客户端关闭JavaScript时,这是不可能的。

How can I solve this? 我怎么解决这个问题?

Is there a way to call the server synchronously or delay render() ? 有没有办法同步调用服务器或延迟render()

In order to get it working, I had to do 3 things: 为了让它工作,我必须做三件事:

  • Replace componentWillMount with getInitialProps() method getInitialProps()方法替换componentWillMount
  • Combine fetch with await and return the data fetchawait结合并返回数据
  • Use this.props instead of this.state 使用this.props而不是this.state

Code looks like this now: 代码现在看起来像这样:

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

Then, in render() I can access the data via this.props.video , for example: 然后,在render()我可以通过this.props.video访问数据,例如:

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

You can add static async getInitialProps () {} to load data into props before the page component gets rendered. 您可以添加static async getInitialProps () {}以在呈现页面组件之前将数据加载到props中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 外部Web服务将用户重定向并将数据发布到我的回调URL。 如何在Express / Next.js应用程序中将发布的数据呈现给用户? - External web service redirects the user and posts data to my callback URL. How do I render the posted data to the user in an Express/Next.js app? Next.js 在初始渲染时从 api 获取令牌并存储它 - Next.js fetch a token from an api on initial render and store it 使用 Node.js 服务器为 Next.js 授权 Azure 存储服务 REST API - 从 URL 复制 Blob - Authorization of Azure Storage service REST API for Next.js with Node.js server - Copy Blob From URL 在 Next.js 中获取数据 - fetching data in Next.js 如何从 next.js 中提取下一个/图像 - How to abstract next/image from next.js 如何在 Next.js 中实现 React hook Socketio - How To Implement React hook Socketio in Next.js 如何在 Next.js React Framework 中构建自定义/动态路由 - How to build custom / dynamic routing in Next.js React Framework Next.js:如何在服务器端持久化数据以从页面调用访问它 - Next.js: how to persist data server-side to access it from page calls 如何在next.js的客户端上重新获取api数据? - How to refetch api data on client side in next.js? 如何使用从Node js到React js的响应数据呈现页面? - How to render page with a response data from node js to React js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM