如何在React中使用服务器端呈现进行API调用

时间:2017-08-20 07:04:37

标签: javascript reactjs serverside-rendering

我有服务器端渲染和运行,但我无法弄清楚如何在我的渲染中包含来自外部API的数据。这是我的核心文件。

server.js

import express from 'express'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { StaticRouter } from 'react-router-dom'
import template from './template'  // the html template
import App from './client'

const server = express()

server.get('*', (req, res) => {
  const context = {}
  const appString = renderToString(
    <StaticRouter location={req.url} context={context}>
      <App/>
    </StaticRouter>
  );

  res.send(template({
    body: appString,
    title: 'SSR',
  }));
});

const port = 8080;
server.listen(port);
console.log(Listening on port ${port})

client.js

import React from 'react';
import { render } from 'react-dom'
import { Router, BrowserRouter, Route, Switch } from 'react-router-dom'

import Home from './containers/Home'

const App = () => (
  <Switch>
    <Route path='/' exact component={Home} />
  </Switch>
)

if (typeof window !== 'undefined') {
  render(
    <BrowserRouter><App /></BrowserRouter>, 
    document.getElementById('root')
  )
}

export default App

Home.js

import React from 'react'
import Layout from './Layout'

import someAction from '../actions/SomeAction'  // this action calls an external api

export default class Home extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            data: null
        }
    }

    // Somehow use "someAction" to hydrate this.state.data so the render
    // can return data from an external api

    render() {
            return (
                <Layout>
                    {this.state.data}
                </Layout>
            )
        }
    }
}

该代码仅用于简单概述我如何使用React进行服务器端渲染。我的问题是如何使用调用外部api的操作并将返回的数据包含在组件render()中。我认为这是server.js renderToString()完整HTML的唯一方法。

0 个答案:

没有答案