【问题标题】:React.js fetch Giphy APIReact.js 获取 Giphy API
【发布时间】:2018-07-15 21:12:33
【问题描述】:

我正在构建一个搜索引擎(使用 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'));

我在控制台中收到以下错误: Uncaught (in promise) TypeError: _this2.setState is not a function 在 eval (index.js:64) 在

感谢任何帮助 :) 谢谢!

【问题讨论】:

  • 在构造函数中使用{this.handleTermChange.bind(this)}或添加this.handleTermChange = this.handleTermChange.bind(this)

标签: javascript reactjs fetch-api


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2022-01-22
    相关资源
    最近更新 更多