Javascript React.js获取Giphy API
我正在构建一个搜索引擎(with React.js),在那里我可以使用GIPHY Gif的API查找GIPHY Gif。我是React.js的新手,在正确编写代码时遇到了一些问题Javascript React.js获取Giphy API,javascript,reactjs,fetch-api,Javascript,Reactjs,Fetch Api,我正在构建一个搜索引擎(with React.js),在那里我可以使用GIPHY Gif的API查找GIPHY Gif。我是React.js的新手,在正确编写代码时遇到了一些问题 import React from 'react'; //react library import ReactDOM from 'react-dom'; //react DOM - to manipulate elements import './index.css'; import SearchBar from '.
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'));
从“React”导入React//反应库
从“react dom”导入react dom//react DOM-操作元素
导入“./index.css”;
从“./components/Search”导入搜索栏;
从“./components/SelectedList”导入礼品列表;
类根扩展React.Component{//Component,该组件将作为应用程序其余部分的父级。
构造函数(){
超级();
此.state={
gifs:[]
}
}
handleTermChange(期限){
控制台日志(术语);
//---------------------->
让url为空http://api.giphy.com/v1/gifs/search?q=${term}&api_key=dc6zaTOxFJmzC';
获取(url)。
然后(response=>response.json())。然后((gifs)=>{
控制台日志(gifs);
控制台日志(gifs.长度);
这是我的国家({
吉布斯:吉布斯
});
});//此
不是以ES6样式语法自动绑定的
您必须在构造函数中绑定:
```
超级()
或对相关函数使用箭头函数语法:
func=()=>{};
参考:使用{this.handleTermChange.bind(this)}
或将this.handleTermChange=this.handleTermChange.bind(this)
添加到构造函数中。
this.state = {
gifs: []
}
this.handleTermChange = this.handleTermChange.bind(this)```