2014-04-16 12 views
13

A destra, probabilmente mi manca l'ovvio ma sto ottenendo un 'tipo non rilevato' Errore: non definito non è una funzione 'Mi sembra di essere .map() che è il problema ma non riesco a capire perché..map() undefined non è una funzione in React.js

var idealist = React.createClass({ 
loadCommentsFromServer: function() { 
    $.ajax({ 
     url: this.props.url, 
     dataType: 'json', 
     success: function(data) { 
      this.setState({data: data}); 
     }.bind(this) 
    }); 
}, 
handleButtonClick: function(input) { 
    // do stuff // 
}, 
getInitialState: function() { 
    return {data: []}; 
}, 
componentWillMount: function() { 
    this.loadCommentsFromServer(); 
    setInterval(this.loadCommentsFromServer, this.props.pollInterval); 
}, 
render: function() { 
    var clickFunction = this.handleButtonClick; 
    var ideas = this.state.data.map(function(i){ 
     return <ideabox data={i} onButtonClick={clickFunction} />; 
    }); 
    return (
     <div className="idealist"> 
      {ideas} 
     </div> 
     ); 
} 
}); 

React.renderComponent(
<idealist url="/json/quotes.php" pollInterval={2000}/>, 
document.getElementById('quoteList') 
); 

Se cambio a idee var = this.state.data non ottengo errori, i dati JSON è formattata correttamente, che cosa può essere sbagliato?

+0

Sei sicuro che this.state.data è un array? – Hatsjoem

+0

['map'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) è una funzione sull'array di JavaScript; non è definito da React. Assicurati che 'this.state.data' sia una matrice. –

+0

Ecco perché sono confuso, lo stato, per quanto ne so, deve essere un array e lo stato.data è definito in getInitialState: function() { return {data: []}; } ,. state.data viene aggiornato da loadCommentsFromServer. Lo script in questione sta restituendo dati JSON correttamente formattati – t1m0thy

risposta

15

È stato uno sbaglio stupido, quotes.php non restituiva dati JSON formattati correttamente, quindi non era un array .map() che veniva chiamato. La lezione ha imparato? Non far credere ad altre persone che il loro codice funzioni!

5

.map() è un metodo che crea una nuova matrice con i risultati forniti.

Ecco la documentazione per questo:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

La cosa che si può fare qui sarebbe per modificare la proprietà .data dell'oggetto per restituire un array. Poiché lo .map() funzionerebbe solo sugli oggetti di tipo Array.

+0

In realtà, 'map' funziona su qualsiasi array come oggetto, ma è necessario impostare il valore' this' esplicitamente tramite '.call' o' .apply' o duck type. –

Problemi correlati