如何使用React.js在Sails.js上呈现服务器端模板?

问题描述 投票:7回答:2

我正在尝试使用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可以正常工作(我将Webpack与babel-loader结合使用)。

javascript node.js reactjs sails.js
2个回答
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 default,它允许从您的模块中导出单个对象。

export default class Auth extends React.Component {}

因此,您可以将模块导入为没有花括号的单个对象。

import Auth from 'auth';

然后您需要使用JSX语法React.renderToString(<Auth />);React.createElement(Auth);

您可以阅读有关ECMA Script 6中模块如何工作的全部信息here


0
投票

[如果其他人对Sails服务器端渲染感兴趣,我会遇到这个项目https://github.com/Noitidart/sails-react-ssr。让我们用ReactDOMServer渲染后端。

© www.soinside.com 2019 - 2024. All rights reserved.