【问题标题】:Rails-React not working with ES6Rails-React 不适用于 ES6
【发布时间】:2016-03-18 15:19:31
【问题描述】:

我正在使用 react-rails gem,我正在尝试在 ES6 中编写一些看起来像这样的组件。

我的 link_list.js.jsx 文件

import Component from 'react';
import Links from 'link';

class LinkList extends React.component{
  constructor(props){
    super(props);
    this.sate = {};
  }

  getInitialState(){
    return { links: this.props.initialLinks}
  }


  render(){
    var links = this.state.links.map(function(link){
      return <Links key={link.id} link={link} />
    })

    return (
      <div className="links">
        {links}
      </div>
    )
  } 
}

我不断收到这个Uncaught ReferenceError: require is not defined 还有一个错误,上面写着Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).

还有错误Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

这是我的代码有问题还是 gem 没有编译 ES6 的问题?

【问题讨论】:

    标签: javascript ruby-on-rails ruby reactjs react-rails


    【解决方案1】:

    生成命令中有一个选项

    rails generate react:component Label label:string --es6

    https://github.com/reactjs/react-rails#options

    否则,您可以使用webpack 设置前端并使用babel

    【讨论】:

    • 我想我应该更多地使用 RTFM 哈哈:P 谢谢你这是完美的
    【解决方案2】:

    通常 React 代码必须“编译”,通常使用 Babel。

    由于这不是“RoR”问题,我建议将 Rails 和 React 分开,在 RoR 中添加额外的 JS 层会令人困惑,更难调试且不必要。

    您必须使用 webpack 生成一个 bundle.js 文件并从您的 rails 布局中调用它,这样 RoR 和 React 就不会相互污染。首先使用 npm 安装您需要的软件包,例如:

     $ npm i react --save
     $ npm i babel-preset-es2015 --save
    

    然后编译 bundle.js

    webpack -d --display-reasons --display-chunks --progress
    

    我当前的 webpack 文件:

    https://github.com/aarkerio/vet4pet/blob/master/webpack.config.js

    使用“webpack -w”选项,这样当你对 .jsx 文件进行更改时,bundle.js 会自动更新。

    您需要在浏览器上激活源映射来调试您的代码。

    【讨论】:

    • 由于 javascript 是您的 Web 应用程序的一部分,我有不同的看法,并说这是一个 RoR 问题。资产指纹呢?为什么想要在 RoR 中包含 CoffeeScript、Sass 编译与想要在资产编译过程中包含 React 有什么不同?我并不是说这很容易——我的意思是我宁愿我的 React 应用程序存在于 Rails 中——我将它视为网站生态系统的一部分,因此更喜欢解决方案而不是保持这种状态。
    猜你喜欢
    • 2017-01-28
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 2016-04-24
    • 1970-01-01
    • 2022-10-09
    • 1970-01-01
    相关资源
    最近更新 更多