【问题标题】:Uncaught TypeError with React.js (GIPHY API)使用 React.js (GIPHY API) 未捕获的 TypeError
【发布时间】:2018-11-29 00:30:56
【问题描述】:

我正在构建一个搜索引擎(使用 React.js),我可以在其中使用他们的 API 查找 GIPHY gif。当我在搜索栏中输入一个单词时,我收到此错误:Uncaught (in promise) TypeError: props.gifs.map is not a function 在 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;

感谢任何帮助!谢谢! :)

【问题讨论】:

    标签: javascript reactjs fetch-api


    【解决方案1】:

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

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

    【讨论】:

    • 你能举个例子吗? @kevvor
    • 我已经检查过了,它实际上是一个数组。这个问题可能来自其他地方。 @kevvor
    【解决方案2】:

    你在这里调用 api 的方式是错误的,因为 this.setState 调用是错误的,而不是写 gifs:gifs 你最好调用它,因为下面的代码使用 axios 也非常快:

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

    【讨论】:

      猜你喜欢
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多