gpt4 book ai didi

javascript - React.js 获取 Giphy API

转载 作者:行者123 更新时间:2023-11-30 11:24:16 25 4
gpt4 key购买 nike

我正在构建一个搜索引擎(使用 React.js),我可以在其中使用他们的 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 './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'));

我在控制台中收到以下错误:未捕获( promise )类型错误:_this2.setState 不是函数 在 eval (index.js:64) 在

感谢任何帮助 :) 谢谢!

最佳答案

this 在 ES6 风格语法中不是自动绑定(bind)的。

你必须在构造函数中绑定(bind):``` super ();

this.state = {
gifs: []
}
this.handleTermChange = this.handleTermChange.bind(this)```

或对相关函数使用箭头函数语法:
函数 = () => {};

供引用:https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

关于javascript - React.js 获取 Giphy API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48632303/

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