【问题标题】:How to use React.js to render server-side template on Sails.js?如何使用 React.js 在 Sails.js 上渲染服务器端模板?
【发布时间】:2015-12-01 11:16:57
【问题描述】:

我正在尝试使用 Sails.js 和 React 构建一个同构应用程序。客户端部分很简单。但是我遇到了服务器端渲染的问题。

当我尝试使用 React 对 *.jsx 文件进行服务器渲染时,我得到了这个:

renderToString(): You must pass a valid ReactElement

我正在使用sailsjs、react 和sails-hook-babel(用于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)。

【问题讨论】:

    标签: javascript node.js reactjs sails.js


    【解决方案1】:

    您的问题不在于您的组件本身,而在于您如何从模块中导出它。

    当只使用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 default,它允许从您的模块中导出单个对象。

    export default class Auth extends React.Component {}
    

    这样您就可以将模块作为一个没有花括号的单个对象导入。

    import Auth from 'auth';
    

    然后您需要使用 JSX 语法 React.renderToString(&lt;Auth /&gt;); 或 React.createElement(Auth);

    您可以阅读有关 ECMA 脚本 6 中的模块如何工作的所有内容here

    【讨论】:

    • 对我感到羞耻,但我不明白 :( 试过 var markup = React.renderToString( React.createElement(Auth) ); 没用。
    • 非常感谢!对于答案和链接,它非常有用。
    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 2013-02-11
    • 2012-04-27
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    相关资源
    最近更新 更多