2016-03-18 48 views
0

我想在async.series塊的第三個函數中調用self.setState({ date_data: tour_dates});。所以我有一個嵌套的函數,看起來甚至在每個塊上使用.bind(this)似乎並不能解決我的問題。我錯過了什麼?我應該怎樣改變我的編碼風格以避免這樣的問題?反應:「this」在組件函數中未定義

var mysql = require('mysql'); 

var async = require('async'); 

var self = this; 
var moment = require('moment'); 

class ArtistTable extends React.Component { 
    constructor(props, context) { 
    super(props, context); 
    this.getArtistData = this.getArtistData.bind(this); 
    this.state = { 
     open: false, 
     date_data: [], 
    }; 
    } 

    getArtistData (artistName) { 

    var artist_id = -1; 
    var tour_id = -1; 
    var tour_dates = new Array(); 
    var connection = mysql.createConnection({ 
     host  : '127.0.0.1', 
     user  : 'root', 
     password : '', 
     database : 'anand2' 
    }); 

    connection.connect(function(err) { 
     if (err) { 
      console.error('MYSQL Error Connecting!' + err.stack); 
      return; 
     } 
     console.log('MYSQL ArtistTable connected as ' + connection.threadId); 
    }); 

    async.series([ 
     function(callback){ 
      connection.query("SELECT * FROM artist WHERE name = '" +artistName+"'" , function(err, rows){ 
       artist_id = rows[0].id; 
       callback(); 
      }); 
     }, function(callback){ 
      //finde tour ID 
      connection.query("SELECT * FROM tour WHERE artist = " + artist_id , function(err, rows){ 

       console.log("SELECT * FROM tour WHERE artist = " + artist_id) //Todo: neue erstellen 
       console.log(rows.length) 
       tour_id = rows[0].id; 

       console.log("Tour ID is " + tour_id) 
       callback(); 
      }); 
     }, function(callback){ 
      connection.query("SELECT dtime,location FROM tour_date WHERE tour="+ tour_id + " AND dtime >= CurDate() ORDER BY dtime ASC" , function(err, rows){ 
       if (rows.length > 0) { 
        for (var i = 0; i < rows.length; i++) { 
         tour_dates.push({date: rows[i].dtime, location: rows[i].location }); 
        } 
        console.log("Number of dates: " + tour_dates.length) 
        self.setState({ date_data: tour_dates}); 
       } 
      }.bind(this)); 
     } 
    ]); 
    } 
} 

此外,請忽略「self = this」,這是一個測試,我也試過這個。

回答

0

您需要在async.series之前將self = this放入getArtistData中。

相關問題