2015-09-05 90 views
6

我想用Sails.js和React構建一個同構應用程序。客戶端部分很容易。但是我遇到了服務器端渲染的問題。如何使用React.js在Sails.js上渲染服務器端模板?

當我嘗試服務器渲染的* .jsx文件反應,我得到這個:

renderToString(): You must pass a valid ReactElement 

我使用sailsjs,反應和帆鉤 - 巴貝爾(用於ES6語法)。

./assets/components/Auth.jsx:

import React from 'react'; 

export class Auth extends React.Component { 
    constructor(props) { 
    super(props); 
    } 

    render() { 
    return (
     <div className='auth'> 
     Very simple element without any logic just for test server-rendering. 
     </div> 
    ); 
    } 
} 

./api/controllers/AuthController.js:

var Auth = require('./../../assets/components/Auth.jsx'); 
import React from 'react'; 

module.exports = { 
    render: function (req, res) { 
    //var markup = React.renderToString(
    // Auth 
    //); // This throws an error 

    console.log(Auth); // {__esModule: true, Auth: [Function: Auth]} 

    //res.view("layout", {app: markup}); 
    } 
}; 

我已經試過到處都ES5/ES6語法。每次都發生錯誤。在客戶端,這個Auth.jsx可以正常工作(我使用帶有babel-loader的webpack)。

回答

5

您的問題不在於您的組件本身,而在於您如何從模塊中導出它。

當僅使用export時,您需要像這樣導入模塊。

import {Auth} from 'auth'; 

只需使用export就可以從模塊中導出超過1件東西。

// My Module. 
export function a(x) { 
    console.log('a'); 
} 

export function b(x, y) { 
    console.log('b'); 
} 

import { a, b } from 'myModule'; 

,或者您可以使用import * from 'myModule'; 這就是所謂的名爲export

您的使用案例要求的是使用export default,它允許從您的模塊中導出單個對象。

export default class Auth extends React.Component {} 

因此,讓您將模塊作爲單個對象導入,而不用大括號。

import Auth from 'auth'; 

然後,你需要使用渲染要麼使用JSX語法React.renderToString(<Auth />);React.createElement(Auth);

你可以閱讀所有關於ECMA腳本6個模塊的工作方式對我here

+0

恥辱,但我不知道得到它:(嘗試'var markup = React.renderToString( React.createElement(Auth) );'沒有工作 – user3278087

+0

非常感謝!對於答案和鏈接,這是非常有用的。 – user3278087

相關問題