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

时间:2015-10-28 23:46:47

标签: javascript reactjs react-router

我无法通过react,react-dom和react-router的服务器实现来访问DOM。我要么有ReferenceError:没有定义文档,要么浏览器历史记录需要DOM错误。

服务器条目:

<?php 

function createButtons($data)
{
    /**
     * [$html Here is where the html buttons are going to be stored]
     * @var string
     */
    $html = '';

    /**
     * This will generate Html Button for each element in the array and concatenate into $html as string like this:
     * <button>
     * <button>
     */
    foreach($data as $button)
        $html .= Html::Button($data['name'], $data['options'])."\n"; //This "\n" adds a new line in the string

    return $html;
}

client.js:

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

routes.jsx:

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

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

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

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