gpt4 book ai didi

javascript - 使用 map() 返回数组时 Uncaught Error

转载 作者:行者123 更新时间:2023-12-01 02:27:18 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于javascript - 使用 map() 返回数组时 Uncaught Error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48642852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com