我正在构建一个搜索引擎(用React.js),在那里我可以使用他们的API查找GIPHY。当我在搜索栏中键入一个单词时,会得到以下错误:Uncaught (承诺) 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;任何帮助都是非常感谢的!谢谢!:)
发布于 2018-02-05 23:48:21
我认为错误(TypeError)是指对象props.gifs不是数组。
我将检查以确保props.gif是一个数组,并且您实际上是在从AJAX请求返回的gifs数组上调用.map()。
发布于 2018-11-28 16:30:56
如何调用api在这里是错误的,因为在这里,this.setState调用是错误的,而不是编写gifs: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以使用此代码。
https://stackoverflow.com/questions/48633273
复制相似问题