我已经成功地让 ReactJS 在服务器端工作,但是我很难集中精力让我的客户端做出响应。
就像我需要打开所有东西一样。我不是通过 ajax 或任何东西来获取数据,任何数据都在组件本身的 JSON 中。
我看到很多文字建议,但没有关于如何让它工作的确切代码。另外,我正在使用反应路由器。
附加背景,我正在使用 commonJS 和 grunt 来编译它。我将编译后的 JS 包含在我的 html 文件中。当我单击按钮等时,什么也没有发生。
服务器:
var React = require('react');
var Router = require('react-router');
var Express = require('express');
var fs = require('fs');
var routes = require('./src/routes');
var app = Express();
app.use('/dist', Express.static(__dirname + '/dist'));
app.use(function (req, res) {
// pass in `req.url` and the router will immediately match
Router.run(routes, req.url, function (Handler) {
var content = React.renderToString(React.createElement(Handler, null));
var index = fs.readFileSync('index.html', {encoding: 'utf8'});
res.send(index.replace('%%%content%%%', content));
});
});
var server = app.listen(9001, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
路由器:
var React = require('react');
var Router = require('react-router');
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
//TODO: dynamically load each route somehow...
var App = require('./app');
var Home = require('./home');
var ItemInstance = require('./item-instance');
var Todo = require('./todo');
var Task = require('./task');
var Project = require('./project');
var Workspace = require('./workspace');
var routes = (
<Route name="index" path="/" handler={App}>
<Route name="home" path="/home" handler={Home} />
<Route name="workspace" path="/workspace" handler={Workspace} />
<Route name="instanceitem" path="/:tag/:id" handler={ItemInstance} />
<DefaultRoute handler={Home}/>
</Route>
);
module.exports = routes;