javascript - 如何在 React.js 前端应用程序中显示来自 Rails 5 API 的数据?

标签 javascript ruby-on-rails json reactjs rails-api

我已经使用 Rails 设置了一个 API,其中的 http://localhost:3001/api/words 端点公开了以下数据:

[{"id":1,"term":"Reach","definition":"Reach is the number of people who had any content from your Page or about your Page enter their screen.","example":"","author":"Loomly","credit":"https://www.loomly.com/","created_at":"2018-11-02T03:21:20.718Z","updated_at":"2018-11-02T03:21:20.718Z"},{"id":2,"term":"Emoji","definition":"A small digital image or icon used to express an idea, emotion, etc., in electronic communication","example":"","author":"Loomly","credit":"https://www.loomly.com/","created_at":"2018-11-02T03:23:50.595Z","updated_at":"2018-11-02T03:23:50.595Z"}]

我现在尝试在使用 Create React App 构建的 React.js 前端应用程序中简单地显示这些数据(最好是无序列表),这是我的 App 的内容.js 文件:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor () {
    super()
    this.state = {}
    this.getWords = this.getWords.bind(this)
    this.getWord = this.getWord.bind(this)
  }

  componentDidMount () {
    this.getWords()
  }

  fetch (endpoint) {
    return window.fetch(endpoint)
      .then(response => response.json())
      .catch(error => console.log(error))
  }

  getWords () {
    this.fetch('/api/words')
      .then(words => {
        if (words.length) {
          this.setState({words: words})
          this.getWord(words[0].id)
        } else {
          this.setState({words: []})
        }
      })
  }

  getWord (id) {
    this.fetch(`/api/words/${id}`)
      .then(word => this.setState({word: word}))
  }

  render () {
    let {words, word} = this.state
    return (
      <div>
        {Object.keys(words).map((key) => {
          return (
            <div key={word.id}>
              <p>{word.term}</p>;
            </div>
          )
        })}
      </div>
    )
  }
}

export default App;

我认为问题出在代码的以下区域:

render () {
  let {words, word} = this.state
    return (
      <div>
        {Object.keys(words).map((key) => {
          return (
            <div key={word.id}>
              <p>{word.term}</p>;
            </div>
          )
        })}
      </div>
    )
}

我已尝试按照 this tutorial 中说明的步骤进行操作,以及 that other tutorial ,同时保持页面布局尽可能简单(没有来自 semantic-ui-css 的花里胡哨),无论我尝试什么,我都会遇到以下错误:

  • 类型错误:无法将未定义或 null 转换为对象
  • 意外的标记,应为“,”
  • 编译失败:“word”未定义 no-undef

this article中解释的解决方案引导我找到了现在的代码,但是我在构建 React 应用程序的方式上缺少一些东西:你能给我指出正确的方向吗?

最佳答案

getWords () {    
  fetch('http://localhost:3001/api/words')
  .then((response) => {
    return response.json();
  })
  .then((res) => {
    // console.log(res); you should get the response you mentioned
    this.setState({words: res});
  });
}

然后检查您是否通过控制台获取您所在州的数据。

然后您可以使用以下方法进行处理

render{
 return(
   <div>
     { this.state.words.map((val) => (
         <span>{val.term}</span>
     ))}
   </div>
 )
}

关于javascript - 如何在 React.js 前端应用程序中显示来自 Rails 5 API 的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53166708/

相关文章:

json - 从 Azure 返回发布凭据作为 json 输出

javascript - 使用 Postman 发帖时 Req 没有​​正文

javascript - Prop 仅在我刷新页面后呈现

跨节点的javascript选择: how to retrieve those nodes?

ruby-on-rails - Rails 4 JSON::ParserError (757: 'null' 处的意外标记):

iphone - Rails 上的服务器推送解决方案

javascript - 影子 DOM 和 ReactJS

mysql - ActiveRecord 请求过多

javascript - 我无法使用 Angular 从 API 检索数据

Python print 和 json.dumps 更改浮点值