如何遍历JavaScript对象中的所有成员,包括作为对象的值.
例如,我怎么能循环这个(访问每个的"your_name"和"your_message")?
var validation_messages = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": "billy",
"your_msg": "foo equals bar"
}
}
Run Code Online (Sandbox Code Playgroud) 我试图使用用户代理将json设置为一个状态,我得到错误:
设置状态的方法:Uncaught Invariant Violation:对象无效作为React子对象(找到:带有键{...}的对象).如果您要渲染子集合,请使用数组,或使用React附加组件中的createFragment(object)包装对象.
getInitialState: function(){
return {
arrayFromJson: []
}
},
loadAssessmentContacts: function() {
var callback = function(data) {
this.setState({arrayFromJson: data.schools})
}.bind(this);
service.getSchools(callback);
},
componentWillMount: function(){
this.loadAssessmentContacts();
},
onTableUpdate: function(data){
console.log(data);
},
render: function() {
return (
<span>{this.state.arrayFromJson}</span>
);
}
Run Code Online (Sandbox Code Playgroud)
服务
getSchools : function (callback) {
var url = 'file.json';
request
.get(url)
.set('Accept', 'application/json')
.end(function (err, res) {
if (res && res.ok) {
var data = res.body;
callback(data);
} else {
console.warn('Failed to load.');
}
});
}
Run Code Online (Sandbox Code Playgroud)
JSON … 我有ControlSection
一个组件,它的道具之一是statistics
对象道具。我想显示<h2>
对象的所有键和值。我该怎么做?
控制部分:
const ControlSection = ({ statistics }) => {
return (
<div className='gameStatistics'>
{
Object.keys(statistics).forEach(key =>
<h2>key: statistics[key]</h2>
)
}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
统计示例:
const statistics = {
Score: score,
Level: level,
Best: bestScore,
};
Run Code Online (Sandbox Code Playgroud)