【问题标题】:Cannot access DOM with server-side render - react 0.14.1, react-dom 0.14.1 and react-router 1.0.0-rc3无法使用服务器端渲染访问 DOM - react 0.14.1、react-dom 0.14.1 和 react-router 1.0.0-rc3
【发布时间】:2016-01-28 23:08:28
【问题描述】:

我无法通过 react、react-dom 和 react-router 的服务器实现访问 DOM。我要么有 ReferenceError: document is not defined,要么浏览器历史记录需要 DOM 错误。

服务器入口:

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');
    }
  })
};

client.js:

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

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

routes.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;

提前感谢您的帮助。

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

再次查看React Router server rendering guide。您只在客户端呈现带有浏览器历史记录的&lt;Router&gt;;在服务器上,您只需将 路由(但不是 &lt;Router&gt;)传递给 &lt;RoutingContext&gt;

【讨论】:

  • 修复了 DOM 错误,但 match 回调中的 renderProps 现在为我包含的路由返回 null。有什么想法吗?
  • 您遇到了哪种错误情况?确保您拥有的 URL 与您拥有的路由配置实际匹配。首先尝试确保仅使用客户端路由。
  • 正在将路由错误地导入文件中 - 让匹配现在正常工作。谢谢。
  • @almccann 您是否愿意使用最终适合您的方法更新您的问题(或添加其他答案)?通过这种方式,这个问题对 Google 员工会变得更有用。
猜你喜欢
  • 2020-03-30
  • 2016-03-26
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 2022-06-16
  • 2022-07-28
  • 2016-01-27
相关资源
最近更新 更多