【问题标题】:React rails rendering home page viewReact rails 渲染主页视图
【发布时间】:2018-04-16 23:17:04
【问题描述】:

我有 Rails API 并响应单独的应用程序。我可以从控制台中的 rails view 主页获取数据。如何使用反应渲染它?我的反应代码如下:

    import React, { Component } from 'react';
    import axios from 'axios'

    class HomePage extends Component {

      componentDidMount(){
        axios.get('http://localhost:3001/')
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
      }
      render(){
        return(
          <h1>{this.response}</h1>
        )
      }
    }

export default HomePage

【问题讨论】:

    标签: ruby-on-rails reactjs axios rack-cors


    【解决方案1】:

    您可以将响应存储在 state 例如为data,然后渲染this.state.data

    【讨论】:

      【解决方案2】:

      如果你想在你的渲染中这样调用它,你需要全局声明response。你现在拥有它的方式,this.response 不附加任何东西。科林一针见血——

      class HomePage extends Component {
            constructor(){
              super();
              this.state = {
                heading: ''
              }
            }
      
            componentDidMount(){
              axios.get('http://localhost:3001/')
              .then(function (response) {
                this.setState({
                  heading: response.data
                })
                console.log(response.data);
              })
              .catch(function (error) {
                console.log(error);
              });
            }
      
            render(){
              return(
                <h1>{this.state.data}</h1>
              )
            }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-08
        • 2013-05-19
        相关资源
        最近更新 更多