简体   繁体   中英

Uncaught TypeError with React.js (GIPHY API)

I'm building a search engine (with React.js), where I can look for GIPHY gifs, using their API. When I type a word in the search bar, I get this error: Uncaught (in promise) TypeError: props.gifs.map is not a function at GifList (SelectedList.js:19)

The code where the API fetch occurs :

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'));

The error comes from the code below:

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 from ./SelectedListItem :

import React from 'react';

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

 export default GifItem;

Any help is appreciated! Thanks! :)

I believe the error (TypeError) is suggesting that the object props.gifs is not an array.

I would check to make sure props.gif is an array, and that you are actually calling .map() on the returned array of gifs from your AJAX request.

How you call the api is wrong here because in, this.setState calling is wrong instead of writing gifs:gifs you should better call it as the code below sice using axios is very also fast:

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})
}

you should also import axios to use this code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM