首页 文章

使用Webpacker的Rails 5.1 App中没有显示React Component

提问于
浏览
1

我有一个使用React通过Webpacker的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>
//...

1 回答

  • 0

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

相关问题