2016-12-19 24 views
2

我試圖保存一個獲取請求的狀態屬性的響應。這裏是我的代碼: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,你是我唯一的希望。

+0

可能是的這個範圍內,在你的代碼屬於jQuery的還沒反應過來 –

+0

不要作出反應混合jQuery的。 jQuery沒有必要。 – ffxsam

回答

3

試試這個。

getTheApi(){ 
    let _this = this; 
    $.get('http://localhost:3008/people', function(cool){ 
    console.log(cool) 
    _this.setState({gets:cool}); 
    }) 
} 

而且在構造函數

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

由於this範圍不提供callbackAJAX請求。你需要將它保存在另一個變量中。

0

你需要做兩件事情

首先:綁定getTheApi()功能,以便它可以訪問狀態

:綁定阿賈克斯成功的功能,而不是狀態

getTheApi =() =>{ 
$.get('http://localhost:3008/people', function(cool){ 
    console.log(cool) 
    this.setState({gets:cool}) 
    }.bind(this)) 
} 
+0

這樣的類屬性是實驗性的 – Li357

3

這個成功回調函數內部沒有引用這個Component。由於您使用ES6,因此您可以使用提供詞彙範圍界定的arrow function

例子:

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