簡體   English   中英

如何在React.js前端應用程序中顯示來自Rails 5 API的數據?

[英]How to display data from Rails 5 API in React.js frontend app?

我已經使用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>
    )
}

我試圖按照本教程以及其他教程中介紹的步驟進行操作,同時使頁面的布局盡可能簡單(無論semantic-ui-css ),無論我如何嘗試,我不斷遇到以下錯誤:

  • TypeError: Cannot convert undefined or null to object
  • Unexpected token, expected “,”
  • Failed to compile: 'word' is not defined no-undef

本文中介紹的解決方案將我帶到了我現在擁有的代碼,但是構建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> ) } 

問題在這里: let {words, word} = this.state ; this.state還沒有文字屬性。 您可以像這樣初始化this.state

this.state = {
   words: [],
   word: {}
};

有空問

問題中的代碼有兩個問題:

  1. wordsword未定義。
  2. 未使用keys正確設置render()函數中的words迭代。

多虧了此問題的答案和評論,這是我最終使用的代碼:

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

class App extends Component {
  constructor () {
    super()
    this.state = {
      words : [],
      word : {}
    }
    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} = this.state
    return (
      <ul className="words-container">
        {Object.keys(words).map((key) => {
          return (
            <li className="word-container" key={key}>
              {words[key].term}: {words[key].definition}.
            </li>
          )
        })}
      </ul>
    )
  }
}

export default App;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM