将服务器端渲染添加到create-react-app

时间:2016-10-21 14:26:22

标签: reactjs redux react-router create-react-app server-rendering

我正在研究create-react-app和SSR。

我在此repo中添加了redux和react-router => https://github.com/sarovin/StarteKit

现在我想添加SSR(服务器端渲染)而不对create-react-app进行任何修改。

我有一个公关,我试图实现它=> https://github.com/sarovin/StarteKit/pull/1

但我有一些错误,因为函数onClick()在我的示例中不起作用:

// App.js

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { switcher } from './actions/switcher';
import logo from './logo.svg';
import './App.css';

const propTypes = {
  switch: PropTypes.bool,
  dispatch: PropTypes.func,
};

class App extends Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }

  onClick() {
    console.log('onClick');
    this.props.dispatch(switcher());
  }

  render() {
    console.log('Switch', this.props.switch);
    return (
      <div className="App">
        <div className="App-header">
          {this.props.switch ? <img src={logo} className="App-logo" alt="logo" /> : null }
          <h2>Welcome to React</h2>
        </div>
        <label className="switch" >
          <input checked={this.props.switch} type="checkbox" onChange={this.onClick} />
          <div className="slider round"></div>
        </label>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    switch: state.switcher.get('switch'),
  };
}

App.propTypes = propTypes;

export default connect(mapStateToProps)(App);

// server.js

import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import hbs from 'express-hbs';
import cors from 'cors';
import React from 'react';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { renderToStaticMarkup } from 'react-dom/server';
import { RouterContext, match } from 'react-router';
import routes from './routes';
import * as reducers from './reducers';

console.log('info', 'Init App');

const app = express();
app.set("port", process.env.PORT || 8080);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// Make index false, so that it is not resolved by default.
app.use(express.static(path.resolve('build'), {index: false}));

app.set("views", path.resolve('build'));
app.set("view engine", "html");
app.engine("html", hbs.express4());

app.use((req, res, next) => {
  match({routes: routes, location: req.url}, (err, redirectLocation, renderProps) => {
    if (err) {
      return res.status(500).send(err.message);
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if(renderProps){
      res.status(200);

      console.log(renderProps);

      const reducer = combineReducers(reducers);
      const initialState = {};
      let store = createStore(reducer, initialState);

      let html = renderToStaticMarkup(
        <Provider store={store}>
          <RouterContext {...renderProps}/>
        </Provider>
      );

      console.log('store', store.getState());
      res.render('index.html', { content: html });
    }
    else res.status(404).send('Page not found');
  });
});

app.listen(app.get("port"), () => {
  console.log("Express server starting on port: " + app.get("port"));
});

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

如果您需要服务器端渲染,我建议使用Next.js而不是create-react-app: https://github.com/zeit/next.js/

答案 1 :(得分:0)

请尝试

https://github.com/antonybudianto/cra-universal

默认情况下无需弹出及其零配置(v3.0.x)

答案 2 :(得分:0)

我强烈建议您为项目razzle。它将您的通用JavaScript应用程序所需的所有工具抽象为单个依赖项,这是SSR的一大收获。

答案 3 :(得分:0)

我一直在考虑同样的事情。我最终得到了一个项目https://github.com/haukurk/cra-ssr-ts-recipe。它是一个同构的Web应用程序,允许您为React进行服务器渲染(支持React Router和Redux)。如果要进行任何预取数据,只需将fetchData函数添加到路径组件即可。

SSR不是微不足道的东西,也不是内置于React / CRA中,并且总是会为您的网络应用程序添加一些额外的工作。

我也一直在研究NextJS,因为人们似乎很赞赏它。我鼓励你看一下。