【问题标题】:React Component is not showing in Rails 5.1 App with Webpacker带有 Webpacker 的 Rails 5.1 应用程序中未显示 React 组件
【发布时间】:2018-06-30 10:08:30
【问题描述】:

我有一个通过 Webpacker 使用 React 的 Rails 5.1 应用程序,并且我的其他组件工作正常,但我尝试的最后一个组件没有显示在页面中。我没有收到任何错误,Firefox 中的 react-dev-tools 没有检测到 React 应用程序。

我已经仔细检查了我是否错过了导入或导出,但在那里看不到错误。

app/javascript/packs/roastsapi.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import RoastFeed from 'RoastFeed'

document.addEventListener('turbolinks:load', function () {
  var element = document.getElementById("roast-feed-component");
  ReactDOM.render(<RoastFeed />, element);
});

app/javascript/RoastFeed/index.jsx

import React from 'react'

class RoastFeed extends React.Component {
  // State:
  // { loading: true }
  // { loading: false, planet: { name, climate, terrain } }
  // { loading: false, error: any }
  state = { loading: true };

  componentDidMount() {
    fetch("https://swapi.co/api/planets/5")
      .then(res => res.json())
      .then(
        planet => this.setState({ loading: false, planet }),
        error => this.setState({ loading: false, error })
      );
  }

  renderLoading() {
    return <div>Loading...</div>;
  }

  renderError() {
    return <div>I'm sorry! Please try again.</div>;
  }

  renderPlanet() {
    const { name, climate, terrain } = this.state.planet;
    return (
      <div>
        <h2>{name}</h2>
        <div>Climate: {climate}</div>
        <div>Terrain: {terrain}</div>
      </div>
    );
  }

  render() {
    if (this.state.loading) {
      return this.renderLoading();
    } else if (this.state.planet) {
      return this.renderPlanet();
    } else {
      return this.renderError();
    }
  }
}

export default RoastFeed

app/views/roasts/index.html.erb

//...
<div id="roast-feed-component"></div>
//...

【问题讨论】:

  • 我不确定可能是什么错误,但该文档对 webpacker-react 很有用,它使用 Turbolinks 进行记录,并且还提供了一个不错的 Rails 助手来渲染您的 React 组件:github.com/renchap/webpacker-react

标签: ruby-on-rails reactjs webpack


【解决方案1】:

您的 webpacker 未配置为支持 jsx 文件。 在扩展名下的 webpacker.yml 文件中添加 - .jsx

【讨论】:

    猜你喜欢
    • 2018-04-23
    • 2017-12-15
    • 1970-01-01
    • 2017-10-10
    • 2018-07-01
    • 1970-01-01
    • 2017-07-24
    • 2018-01-20
    • 2018-04-01
    相关资源
    最近更新 更多