我有一個reactjs組件,我試圖用循環和開關來呈現數據。Reactjs循環通過數組和開關
我試了一個地圖,然後forEach - 但它聲稱它不是一個函數。
json看起來像這樣。
// JSON
"contents": {
"0": ["emotional distress", "behavioural difficulties", "hyperactivity and concentration difficulties", "difficulties in getting along with other young people"],
"5": ["kind and helpful behaviour"]
}
//組件
var YourCurrentStanding = React.createClass({
alertLevel: function (key) {
switch (key) {
case '0': return "very high";
case '1': return "high";
case '5': return "very low";
default: return "xy";
}
},
render: function() {
console.log('this.props.data.contents', this.props.data.contents)
return (
<div>
{
this.props.data.contents.forEach(function(j) {
return <p key={j}>Score for x,y and z {this.alertLevel(j)}</p>
})
}
</div>
);
}
});
-----------應該象
"<p>Score for emotional distress, behavioural difficulties, hyperactivity and concentration difficulties very high and difficulties in getting along with other young people very high</p>
<p>Score for kind and helpful behaviour very low</p>"
附近工作代碼添加了語法檢查
var YourCurrentStanding = React.createClass({
grammarCheck : function(vals) {
//x,y,z and d
//z
return vals.join(', ')
},
alertLevel: function(key) {
switch (key) {
case "0":
return "very high";
case "1":
return "high";
case "5":
return "very low";
default:
return "xy";
}
},
render: function() {
return (
<div>
{Object.keys(this.props.data.contents).map((key, index) => {
return <p key={index}>Score for {this.grammarCheck(this.props.data.contents[key])} is <b>{this.alertLevel(key)}</b></p>
})}
</div>
);
}
});
Use()=> {}函數語法與您的「this」不綁定到您的組件,而是綁定到您的匿名函數。 (我在說你的this.alertLevel) – Nevosis
我在哪裏放 - 我傾向於使用var that = this - 然後調用that.alertLevel(j) –
內容不是數組它是一個對象。所以它沒有forEach方法。您必須遍歷對象鍵,然後遍歷數組。 –