gpt4 book ai didi

javascript - 无法使用服务器端渲染访问 DOM - react 0.14.1、react-dom 0.14.1 和 react-router 1.0.0-rc3

转载 作者:数据小太阳 更新时间:2023-10-29 04:49:22 25 4
gpt4 key购买 nike

我无法使用 react、react-dom 和 react-router 的服务器实现访问 DOM。我有 ReferenceError: document is not defined,或者 Browser history needs a DOM errors。

服务器入口:

module.exports = 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) {
res
.status( 200 )
.set( 'Content-Type', 'text/html' )
.send( '<!doctype html>' +
renderToString(
[ <RoutingContext {...renderProps} />,
<HtmlDocument /> ]
)
);
} else {
res
.status(404)
.send('Not found');
}
})
};

客户端.js:

import { render } from 'react-dom';
import routes from './routes';

render( routes, document.getElementById('app') )

路由.jsx:

import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';

import Application from './Application';
import Index from './pages/index';
import App from './pages/app';
import Auth from './pages/auth';
import Login from './pages/auth/components/Login';
import Signup from './pages/auth/components/Signup';
import NotFound from './pages/notFound';

var routes = (
<Router history={createBrowserHistory()}>
<Route path="/" component={Application}>
<IndexRoute component={Index} />
<Route path="app" component={App} onEnter={ App.requireAuth } />
<Route path="auth" component={Auth} />
<Route path="signup" component={Signup} />
<Route path="login" component={Login} />
<Route path="*" component={NotFound} />
</Route>
</Router>
);

export default routes;

在此先感谢您的帮助。

最佳答案

看看 React Router server rendering guide再次。您只渲染 <Router>客户端上的浏览器历史记录;在服务器上,您只需将路由(而不是<Router>)传递给<RoutingContext> .

关于javascript - 无法使用服务器端渲染访问 DOM - react 0.14.1、react-dom 0.14.1 和 react-router 1.0.0-rc3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33403549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com