jquery - this.setState() 不是一个函数 -> 当尝试保存状态响应时

标签 jquery api reactjs get undefined

我正在尝试将获取请求的响应保存到状态属性上。这是我的代码:

import React, { Component } from 'react';
import {render} from 'react-dom';

import './App.css';
import Card from './Card.js';
import SearchBar from "./SearchBar.js"
import star from './images/star.svg';
import wars from './images/wars.svg';
import $ from './../node_modules/jquery';

class App extends Component {

constructor(props){
  super(props);
  this.state = {
    gets: []      //THIS IS WHERE THE RESPONSE ARR SHOULD BE SAVED 
  }
}

////////////////////////////
//     GET REQUEST        //
////////////////////////////

getTheApi(){
$.get('http://localhost:3008/people', function(cool){
    console.log(cool) //<-- the response is correct (array of objs)
    this.setState({gets:cool}).bind(this)   //have tried w/ w/out .bind(this)
  })
}

render() {

console.log(this.state.gets); //shows as undefined

    return (
      <div className='content'>
        <div className='logo'>
          <img src={star} alt="star-logo" />
          <span className='interview-text'>The Interview</span>
          <img src={wars} alt="wars-logo" />
          <span>WHATTTTTT</span>
        </div>
        <SearchBar />
        <Card />
      </div>
    );
  }
}

render(<App/>, document.getElementById('app'));

我尝试了多种方法来让它发挥作用,但没有成功。我尝试过使用和不使用绑定(bind)的 this.setState({gets:cool}) 。我已经在 this.setState 之前控制台记录了变量 cool,并且我得到了正确的对象数组。但是当我尝试保存我的回复时,它说

Type Error: this.setState() is not a function.

我还尝试在渲染内部调用 getTheAPI() ,认为状态没有更新,因为该函数从未运行过,但错误仍然存​​在。

我只是不明白为什么响应是在函数中定义的,而不是在函数外定义的,以及为什么它说 this.setState() 不是函数。

帮助我,奥比旺·克诺比,你是我唯一的希望。

最佳答案

成功回调函数中的this并不是引用组件的this。由于您使用的是 ES6,因此可以使用 arrow function它提供了词法范围。

示例:

 getTheApi = () => {
     $.get('http://localhost:3008/people', (cool) => {
        this.setState({gets:cool})
     })
 }

关于jquery - this.setState() 不是一个函数 -> 当尝试保存状态响应时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41216948/

相关文章:

reactjs - 将自定义 Prop 传递给 typescript 中的样式组件

javascript - 使用javascript隐藏和显示菜单ID

jquery - 如何使用 jquery sortable 保存表行的顺序而不使用 ".toArray()"或 ".serialize()"?

api - 使用 Sails JS 对 Jira REST API 进行身份验证

reactjs - 登录 React Redux 应用程序后重定向到主页

javascript - 渲染既不是由 setState() 也不是forceUpdate() 触发

javascript - 智能手机固定导航栏在选择后不关闭

javascript - TypeError : jasmine. createSpy(...).andCallFake 不是函数

php - session ID 与 token

ios - 获取应用程序本身的 iOS iTunes App Store ID?