我正在构建一个搜索引擎(和React.js),在那里我可以使用他们的API查找GIPHY。我是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'));我在控制台中得到了以下错误:Uncaught (承诺) TypeError:_this2.setState不是上的 (index.js:64)函数
任何帮助都是感激的:)谢谢!
发布于 2018-02-05 22:12:31
this在ES6样式语法中不是自动绑定的.
您必须在构造函数中绑定:`超级();
this.state = {
gifs: []
}
this.handleTermChange = this.handleTermChange.bind(this)```或对所讨论的函数使用箭头函数语法:func = () => {};
参考:https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
https://stackoverflow.com/questions/48632303
复制相似问题