微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 无法访问服务器端渲染的DOM – 反应0.14.1,react-dom 0.14.1和react-router 1.0.0-rc3

我无法使用react,react-dom和react-router的服务器实现来访问DOM.我要么具有ReferenceError:未定义文档,要么浏览器历史记录需要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;

在此先感谢您的帮助.

解决方法

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

原文地址:https://www.jb51.cc/js/157069.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐