我试图遍历哈希中的所有键,但没有从循环返回任何输出。 console.log()
按预期输出。知道为什么 JSX 没有返回并正确输出吗?
var DynamicForm = React.createClass({
getInitialState: function() {
var items = {};
items[1] = { name: '', populate_at: '', same_as: '',
autocomplete_from: '', title: '' };
items[2] = { name: '', populate_at: '', same_as: '',
autocomplete_from: '', title: '' };
return { items };
},
render: function() {
return (
<div>
// {this.state.items.map(function(object, i){
// ^ This worked previously when items was an array.
{ Object.keys(this.state.items).forEach(function (key) {
console.log('key: ', key); // Returns key: 1 and key: 2
return (
<div>
<FieldName/>
<PopulateAtCheckboxes populate_at={data.populate_at} />
</div>
);
}, this)}
<button onClick={this.newFieldEntry}>Create a new field</button>
<button onClick={this.saveAndContinue}>Save and Continue</button>
</div>
);
}
最佳答案
Object.keys(this.state.items).forEach(function (key) {
Array.prototype.forEach()
不返回任何东西 - 使用 .map()
代替:
Object.keys(this.state.items).map(function (key) {
var item = this.state.items[key]
// ...
关于javascript - react JSX : Iterating through a hash and returning JSX elements for each key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29534224/