簡體   English   中英

使用React.js(GIPHY API)捕獲TypeError

[英]Uncaught TypeError with React.js (GIPHY API)

我正在構建一個搜索引擎(使用React.js),可以在其中使用其API查找GIPHY gif。 當我在搜索欄中鍵入單詞時,出現以下錯誤: 未捕獲(承諾)TypeError:props.gifs.map在GifList上不是函數(SelectedList.js:19)

API提取發生的代碼

import React from 'react'; //react library
import ReactDOM from 'react-dom'; //react DOM - to manipulate elements
import './index.css';
import SearchBar from './components/Search';
import GifList from './components/SelectedList';

class Root extends React.Component { //Component that will serve as the 
parent for the rest of the application.

constructor() {
    super();

    this.state = {
        gifs: []
    }
    this.handleTermChange = this.handleTermChange.bind(this)
}

handleTermChange(term) {
   console.log(term);
    let url = 'http://api.giphy.com/v1/gifs/search?q=${term}&api_key=dc6zaTOxFJmzC';
        fetch(url).
    then(response => response.json()).then((gifs) => {
          console.log(gifs);
          console.log(gifs.length);
          this.setState({
            gifs: gifs
          });
        });
    };  


render() {
    return (
      <div>
        <SearchBar onTermChange={this.handleTermChange} />
        <GifList gifs={this.state.gifs} />
      </div>
    );
}
}

ReactDOM.render( <Root />, document.getElementById('root'));

錯誤來自以下代碼:

import React from 'react';
import GifItem from './SelectedListItem';

const GifList = (props) => {
  ===>const gifItems = props.gifs.map((image) => {<===
    return <GifItem key={image.id} gif={image} />
});

return (
    <ul>{gifItems}</ul>
  );
};

export default GifList;

來自./SelectedListItem的GifItem

import React from 'react';

 const GifItem = (image) => {
   return (
     <li>
       <img src={image.gif.url} />
     </li>
  )
 };

 export default GifItem;

任何幫助表示贊賞! 謝謝! :)

我相信錯誤(TypeError)表示對象props.gifs不是數組。

我將檢查以確保props.gif是一個數組,並且您實際上是在從AJAX請求返回的gif數組中調用.map()

您在這里如何調用api是錯誤的,因為in.this.setState調用是錯誤的,而不是編寫gifs:gifs,因此您最好調用它,因為使用axios的sice下面的代碼也非常快:

handleTermChange = async (term) => {
const response = await axios.get(`http://api.giphy.com/v1/gifs/search?q=${term}&limit=24&api_key=(YOUR APİ_KEY)
  this.setState({gifs:response.data.data})
}

您還應該導入axios以使用此代碼。

暫無
暫無

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

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