如何在反应同构应用程序中渲染之前获取服务器中的数据?

问题描述 投票:0回答:5

我发现了一些aproaches,但它们不能与react-router版本4一起工作。这很奇怪,在文档中没有任何关于它的信息。

reactjs
5个回答
1
投票

https://blog.tableflip.io/server-side-rendering-with-react-and-redux/ - 我在阅读本文后解决了我的问题。


0
投票

你可以看到我的react-ssr-startkit

客户:

class Home extends React.Component {
// some logic
}
Home.serverFetch = {type: 'repos/fetchData'};

服务器:

routes
.filter(route => matchPath(req.url, route))
.map(route => route.component)
.filter(comp => comp.serverFetch)
.map(comp => {
    const {type, payload} = comp.serverFetch;
    return dispatch({type, payload});
});

-1
投票

您需要获取Web服务器上的数据,然后将数据传递给您的(哑)组件,该组件只会呈现而不会执行太多逻辑。

如果需要更新客户端上的数据,请查看套接字解决方案或仅在componentdidmount()中创建间隔提取。

我们目前正在研究这个问题,我们正在使用Airbnb的Hypernova来处理通用渲染,你需要一个网络服务器来允许组件使用我们可以缓存的URL和服务器端包含到我们页面中的URL进行映射。因此,在该网络服务器中,您可以执行获取和传递,因此您可以将组件的初始状态视为html。


-2
投票

您可以在构造函数中使用axios,根据反应Lifecycles,构造函数在render()之前出现;

例:

  constructor(props) {
    super(props);
    this.state = {
      items: [],
    };
    axios.get('http://into-the-feed-api.cloud.globoi.com/') 
    .then(res => {
      const index = this.getIndex(res.data);
      if (index) {
        this.setState({
          items: [res.data[index]].concat(res.data.slice(0, index).concat(res.data.slice(index + 1, res.data.length)) ),
        });
      } else {
        this.setState({ items: res.data }); 
      } 
    });
    this.changeHeaderExpanded = this.changeHeaderExpanded.bind(this);
  }
© www.soinside.com 2019 - 2024. All rights reserved.