2015-11-09 28 views
0

我得到'props.data.map不是函數錯誤'。我也有console.log'this.props.data'在ResultList中,但不知何故它仍然沒有映射。我也嘗試了谷歌和stackoverflow中的所有相關鏈接。Uncaught TypeError:this.props.data.map不是函數(使用superagent)

請指教。任何幫助將不勝感激!!謝謝你們:)

這裏的鏈接顯示響應的截圖: image

var Results = React.createClass({ 
    getInitialState: function() { 
    return {data: []}; 
    }, 

    componentDidMount: function() { 
    // loading results from server for initialization 
    this.loadResultsFromServer(); 
    }, 

    loadResultsFromServer: function() { 
    superagent 
    .get('http://localhost:5000/analyzer') 
    .end(function(err, res){ 
     if (res) { 
     console.log(res); 
     this.setState({data: res.text}); 
     } else { 
     console.log("error loading results from server: ", err); 
     } 
    }.bind(this)); 
    }, 

    render: function() { 
    return (
     <div> 
     <ResultList data={this.state.data} /> 
     </div> 
    ); 
    } 
}); 

var ResultList = React.createClass({ 
    render: function() { 
     var resultNodes = this.props.data.map(function (result) { 
     return (
      <Result name={result.Name}> 
      {result.Score} 
      </Result> 
     ); 
     }); 

     return (
     <div> 
      {resultNodes} 
     </div> 
    ); 
    } 
}); 

回答

0

它看起來像你的res.text是一個字符串,而不是一個數組。這意味着它將不具備.map功能。如果這是您的API返回的響應,則需要在設置狀態時調用JSON.parse,即:

this.setState({ data: JSON.parse(res.text) }); 
+0

謝謝@Jakemmarsh !!但現在我得到了一個警告,即每個孩子都應該擁有一個獨特的「鑰匙」道具。 hmm – Winston

+0

@Winston這意味着我們的'.map'函數輸出的每個項目都需要一個唯一的'key'屬性。實現這一點的最簡單方法是也傳遞索引,即:this.props.data.map(function(result,index){'然後將其作爲prop傳遞:' – Jakemmarsh

相關問題