我試圖保存一個獲取請求的狀態屬性的響應。這裏是我的代碼:this.setState()不是一個函數 - >當試圖保存狀態的響應
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'));
我試過多種方式來得到這個工作,但沒有骰子。我試過this.setState({gets:cool})有和沒有綁定。我之前控制檯登錄變量很酷this.setState之前,我得到正確的對象數組。但是,當我然後嘗試保存我的迴應狀態它說'類型錯誤:this.setState()不是一個函數。
我也嘗試調用渲染內部的getTheAPI(),思考狀態沒有被更新,因爲該函數從未運行,但錯誤仍然存在。
我只是不知道爲什麼在函數中定義了響應,但沒有在函數中定義,爲什麼它說this.setState()不是函數。
幫助我Obi Wan Kenobi,你是我唯一的希望。
可能是的這個範圍內,在你的代碼屬於jQuery的還沒反應過來 –
不要作出反應混合jQuery的。 jQuery沒有必要。 – ffxsam