代码之家  ›  专栏  ›  技术社区  ›  Timmy

返回带有map()的数组时出现未捕获错误

  •  0
  • Timmy  · 技术社区  · 7 年前

    我正在用React构建一个搜索引擎。js,在那里我可以使用他们的API查找GIPHY Gif。当我在搜索栏中键入一个单词时,会出现以下错误: 未捕获(承诺中)类型错误:道具。吉布斯。map不是一个函数 在GifList(SelectedList.js:19)

    控制台日志返回一个数组,很难:

    import React from 'react';
    import GifItem from './SelectedListItem';
    
    const GifList = (props) => {
      console.log(props.gifs); // Logs Array in the console
      const gifItems = props.gifs.map((image) => { // <=======
        return <GifItem key={image.id} gif={image} />
       });
    
      return (
        <div className="gif-list">{gifItems}</div>
      );
    };
    
    export default GifList;
    

    如何获取GIF:

    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.replace(/\s/g, '+')}&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'));
    

    感谢您的帮助!谢谢!:)

    1 回复  |  直到 7 年前
        1
  •  2
  •   Shubham Khatri    7 年前

    根据您的评论, props.gifs 是一个对象,并且 props.gifs.data 是一个数组。所以你需要写

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