[英]React.js fetch Giphy API
I'm building a search engine ( with React.js ), where I can look for GIPHY gifs, using their API. 我正在构建一个搜索引擎( 使用React.js ),在那里我可以使用他们的API查找GIPHY gif。 I'm new to React.js and i'm having some trouble getting this code right.
我是React.js的新手,我在使用此代码时遇到了一些麻烦。
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: []
}
}
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
});
});//<------------------------- THIS CODE HERE
};
render() {
return (
<div>
<SearchBar onTermChange={this.handleTermChange} />
<GifList gifs={this.state.gifs} />
</div>
);
}
}
ReactDOM.render( <Root />, document.getElementById('root'));
I get the following error in the console: Uncaught (in promise) TypeError: _this2.setState is not a function at eval (index.js:64) at 我在控制台中收到以下错误: Uncaught(在promise中)TypeError:_this2.setState不是eval(index.js:64)处的函数
Any help is appreciated :) Thanks! 任何帮助表示赞赏:)谢谢!
this
is not auto-bound in ES6 style syntax. this
不是ES6样式语法中的自动绑定。
You have to bind in the constructor: ``` super(); 你必须在构造函数中绑定:```super();
this.state = {
gifs: []
}
this.handleTermChange = this.handleTermChange.bind(this)```
or use arrow function syntax for the function in question: func = () => {};
或者对有问题的函数使用箭头函数语法:
func = () => {};
For reference: https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding 供参考: https : //facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.