[英].map() undefined is not a function in React.js
是的,我可能在這里遺漏了明顯的信息,但我收到了“未捕獲的類型錯誤:未定義不是函數”我似乎是 .map() 這就是問題所在,但我不明白為什么。
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')
);
如果我將其更改為 var ideas = this.state.data 我沒有收到任何錯誤,JSON 數據格式正確,有什么問題?
這是一個愚蠢的錯誤,quotes.php 沒有返回格式正確的 JSON 數據,所以它不是一個數組 .map() 被調用。 吸取的教訓? 不要相信其他人說他們的代碼有效!
.map()
是一種使用提供的結果創建新數組的方法。
這是文檔:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
您可以在這里做的是更改對象的.data
屬性以返回一個數組。 由於.map()
僅適用於 Array 類型對象。
如果這對任何人有幫助,另一個容易忽視的錯誤是將變量初始化為空對象而不是狀態中的空數組並調用 map()。
例如,在下面聲明
const [list, setList] = useState({});
代替
const [list, setList] = useState([]);
並嘗試在對象上調用 map()
list.map((item)=>{
//do something
})
將導致“undefined is not a function near ... list.map(...” 在加載組件期間出現錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.