带有React.js的未捕获的TypeError(GIPHY API)

时间:2018-02-05 23:39:01

标签: javascript reactjs fetch-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;

GifItem来自./SelectedListItem

import React from 'react';

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

 export default GifItem;

任何帮助表示赞赏!谢谢! :)

2 个答案:

答案 0 :(得分:0)

我认为错误(TypeError)表明对象props.gifs不是数组。

我会检查以确保props.gif是一个数组,并且您实际上正在从您的AJAX请求中返回返回的GIF数组上的.map()

答案 1 :(得分:0)

这里的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以使用此代码。