【发布时间】:2017-08-30 16:00:41
【问题描述】:
我有一个 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>
);
}
});
【问题讨论】:
-
使用 () => {} 函数语法,因为您的“this”不是绑定到您的组件而是绑定到您的匿名函数。 (我说的是你的 this.alertLevel)
-
我把那个放在哪里 -- 我倾向于使用 var that = this -- 然后调用 that.alertLevel(j)
-
Contents 不是数组而是对象。所以它没有 forEach 方法。您必须遍历对象键,然后遍历数组。
-
用map方法?
-
-- 我可以改变数据结构 -- 只是我觉得 0 - 非常高, - 1,高 -- 在键中使用数字而不是单词 -- 将能够确保数据排序正确