2016-09-05 26 views
5

Jestem nowy w React, widziałem niektóre z podobnych problemów, ale nie znalazłem, dlaczego tak się dzieje. Otrzymuję "Uncaught TypeError: this.state.data.map nie jest funkcją". Oto kod. Proszę, pomóż znaleźć problem.Uncaught TypeError: this.state.data.map nie jest funkcją

class Audienses extends React.Component { 

    constructor (props) 
    { 
     super(props); 

     this.state = { 
      data: '' 
     }; 

     this.loadFromServer = this.loadFromServer.bind(this); 
     this.childeDelete = this.childeDelete.bind(this); 
     this.childeEdit = this.childeEdit.bind(this); 

    } 

    loadFromServer() { 
     var xhr = new XMLHttpRequest(); 
     xhr.open('get', this.props.url, true); 
     xhr.onload = function() { 
      var data = JSON.parse(xhr.responseText); 
      this.setState({ data: data }); 

     }.bind(this); 
     xhr.send(); 
    } 

    componentDidMount() { 
     this.loadFromServer(); 
    } 


    render() { 

     var audienses = this.state.data.map((value, index) => (
      <OneElement key={value.id} audience={value.audience} description={value.description} /> 
     )); 

     /* or like this 
     var audienses = this.state.data.map(function(s) { 
      <OneElement key={s.id} audience={s.audience} description={s.description} onDeleteClick={this.childeDelete} oneEditClick={this.childeEdit} /> 
     }).bind(this); 
     */ 
     return 
     <div> 
      <h1>Audiences</h1> 
      <table id="services"> 
       <tr> 
        <th>Audience</th> 
        <th>Description</th> 
        <th></th> 
        <th></th> 
       </tr> 
       <tbody> 
        {audienses} 
       </tbody> 
      </table> 
     </div>; 
    } 
} 

Odpowiedz

12

Początkowej data stan jest String., String nie ma sposobu .map, trzeba zmienić swój stan początkowy z '' do []

this.state = { data: [] }; 
+1

Dziękuję bardzo! Już działa! – Ang

3

.map nie ma zastosowania do obiektu String. Rozważ zmianę "danych" na tablicę. .map to metoda wywołująca funkcję na każdym elemencie macierzy .