简体   繁体   English

使用后端请求来反应服务器端呈现

[英]React server side rendering with backend requests

I have an React app with server side rendering via Express. 我有一个React应用程序,通过Express进行服务器端渲染。 I have simple App component: 我有简单的App组件:

import React, { Component } from 'react';

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      data: []
    };

    fetch('http://backend', {
      mode: 'cors',
    })  
      .then(res => res.json())
      .then(data => this.state.data); 
  }

  render() {
    return (
      <ul> 
        {this.state.data.map(item => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    );
  }
};

The problem (or more probable feature) is that fetch works async. 问题(或更可能的功能)是fetch工作异步。 So browser gets page with empty data. 因此浏览器获取包含空数据的页面。

Is there a way to get from server page with loaded data? 有没有办法从加载数据的服务器页面获取? Let's say I want to get from server page with loaded posts or something else. 假设我想从带有加载帖子或其他内容的服务器页面获取。

Or do I something wrong at all? 或者我有什么不对劲?

You are not setting the state correctly. 您没有正确设置state Use setState() to set the new state as you cannot update the state without using setState() method: https://facebook.github.io/react/docs/react-component.html#setstate 使用setState()设置新状态,因为如果不使用setState()方法就无法更新状态: https//facebook.github.io/react/docs/react-component.html#setstate

fetch('http://backend', {
  mode: 'cors',
})  
.then(res => res.json())
.then(data => this.setState({data: data})); 

Also, the code you have added is not server-side rendering using React. 此外,您添加的代码不是使用React的服务器端呈现。 You use the method ReactDOMServer.renderToString() to do server-side rendering: https://facebook.github.io/react/docs/react-dom-server.html#rendertostring 您使用ReactDOMServer.renderToString()方法进行服务器端呈现: httpsReactDOMServer.renderToString()

Yes, even if you fix the setState() problem you will still be rendering the component before the fetch. 是的,即使你修复了setState()问题,你仍然会在获取之前渲染组件。 The problem is indeed that fetch is asynchronous. 问题确实是fetch是异步的。

To be able to server-side render back-end calls you need to wait until all backend calls have been made, set the props & state for all components and then render them out. 为了能够进行服务器端渲染后端调用,您需要等待所有后端调用,为所有组件设置props和state,然后将其渲染出去。

Two libraries that will help you with figuring out when things are done are Redial ( https://github.com/markdalgleish/redial ) and redux-promise-counter ( https://github.com/bitgenics/redux-promise-counter ) if you are using Redux. 两个可以帮助您搞清楚事情何时完成的库是Redial( https://github.com/markdalgleish/redial )和redux-promise-counter( https://github.com/bitgenics/redux-promise-counter )如果您使用的是Redux。 More on that below. 更多关于以下内容。

The next problem you want to solve is getting that data to the client and initialize your components from that, so you don't have to redo (all) the request(s) on the client again. 您要解决的下一个问题是将数据传输到客户端并从中初始化组件,因此您不必再次在客户端上重做(全部)请求。

You could do all that manually, but if you are serious about SSR, you should probably go for something like Redux. 你可以手动完成所有这些工作,但如果你认真对待SSR,你应该选择像Redux这样的东西。 A way to store all your application state in one store. 一种将所有应用程序状态存储在一个商店中的方法。 Makes it easier to store results, ship it to the client and initialize your store from JSON. 使结果更容易存储,将结果发送到客户端并从JSON初始化商店。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM