React JS:从服务器渲染迁移到纯客户端

时间:2016-02-12 07:02:43

标签: javascript node.js reactjs gulp serverside-javascript

我已经使用节点js服务器进行了反应项目,并使用了客户端和服务器端呈现和路由。我需要移动它,以便它使用纯客户端渲染/路由。我该怎么做呢?

server.js文件如下所示:

var Router = require('react-router').Router;
var routes = require('./public/js/' + defaultAppName + '/' + defaultAppName + '.node.js');

app.get('*', function (req, res, next) {

  var location = new Location(req.path, req.query);

  try {
    Router.run(routes(), location, function (e, i, t) {
      var str = ReactDOMServer.renderToString(
        React.createElement(Router, i));
    });
  } catch (e) {
    console.error(e);
    return next();
  }
});

目录结构如下 -

|- server.js
|- gulpfile.js
|- public
  |- js
    |- app.node.js
|- src
  |-jsx
    |  |-app
    |  |  |-actions
    |  |  |-components
    |  |  |-reducers
    |  |  |-routes
    |  |  |-index.html
  |-sass
    |  |-app
    |  |  |-main

1 个答案:

答案 0 :(得分:1)

从应用程序的服务器端代码和Serve index.html中删除任何网址的路由,并让路由由应用程序入口点处理。例如

var static_path   = path.join(__dirname, 'public');
app.use(express.static(static_path));

     app.get('/', function (req, res) {
         res.sendFile('index.html', {
             root: static_path
         });
     });

app的内部入口点,例如app.jsx

var ReactDom = require('react-dom');
var Routes = require('/path/to/routes');

ReactDom.render(Routes, document.querySelector('.any-place-on-dom'));