我試圖讓反應路由器V1.0工作,但是當我在寫的服務器端渲染路由器,我得到這個錯誤在瀏覽器中:React is undefined
陣營使用ReactDOM
router.js
:
'use strict';
import { Router, Route, match, RoutingContext } from 'react-router';
import routes from './routes';
import {renderToString} from 'react-dom/server';
export default function(req, res, next) {
match({routes, location: req.url}, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message)
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
let markup = renderToString(<RoutingContext {...renderProps} />);
res.render('index', {markup: markup});
} else {
res.status(404).send('Not found')
}
})
};
我這個文件快遞server.js
import express from 'express';
import path from 'path';
import favicon from 'serve-favicon';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import exphbs from 'express-handlebars';
import router from '../shared/routes/router';
import routes from "../shared/routes/routes";
const app = express();
// view engine setup
app.engine('handlebars', exphbs({defaultLayout: 'main', extname: '.handlebars'}));
app.set('views', './views'); // ????
app.set('view engine', 'handlebars');
// uncomment after placing your favicon in /public
app.use(favicon('favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//app.use(require('less-middleware')(path.join(__dirname, 'dist')));
app.use(express.static('./public'));
app.use(router);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
//.... the rest of code
我做的還一樣here。 當我看transpiled代碼(使用babelify)我看到:
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (req, res, next) {
(0, _reactRouter.match)({ routes: _routes2.default, location: req.url }, function (error, redirectLocation, renderProps) {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
res.status(200).send((0, _server.renderToString)(React.createElement(_reactRouter.RoutingContext, renderProps)));
} else {
res.status(404).send('Not found');
}
});
};
var _reactRouter = require('react-router');
var _routes = require('./routes');
var _routes2 = _interopRequireDefault(_routes);
var _server = require('react-dom/server');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
;
但不browserify,babelify和應對路由器想通過把需要的模塊中的代碼來照顧呢?
React.createElement(_reactRouter.RoutingContext, renderProps)
這是爲了運行需要React
參考:
你有沒有試圖導入'React'在react.js? –
你的意思是'router.js'? –
葉氏route.js對不起 –