gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:00:16 25 4
gpt4 key购买 nike

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

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/

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