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

标签 node.js reactjs next.js react-universal

我想使用 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;

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

componentWillMount
render
null
received

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

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

我该如何解决这个问题?

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

最佳答案

为了让它工作,我必须做三件事:

  • componentWillMount 替换为 getInitialProps()方法
  • 结合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>
  );
}

关于node.js - 如何在 React Universal 中呈现从 REST 服务接收到的数据? (Next.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43793115/

相关文章:

javascript - 整合 React-Semantic-UI 和 redux-form

reactjs - 在 React Hooks 项目中应用 Draft Wysiwyg

node.js - 在本地主机上运行时,Firebase 出现 CORS 错误

reactjs - 如何在 Nextjs 布局中使用上下文 Hook

next.js - 如何在 nextjs 13 的元数据中添加 noindex?

node.js - WebSocket 无法发送/接收长度超过 65536 个字符的字符串

javascript - 无法在 Node.js 上使用 URL 模块,无法调用未定义的方法 'parse'

javascript - 如何注销 ipcRenderer.on 事件监听器?

node.js - Nodemailer 附件文本文件

node.js - nodeJS/GitlabCI : How to serve decentralized productive application