React JSX:遍历哈希并为每个键返回 JSX 元素
React JSX: Iterating through a hash and returning JSX elements for each key
我正在尝试遍历哈希中的所有键,但循环没有返回任何输出。 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()
没有 return 任何东西 - 使用 .map()
代替:
Object.keys(this.state.items).map(function (key) {
var item = this.state.items[key]
// ...
快捷方式是:
Object.values(this.state.items).map({
name,
populate_at,
same_as,
autocomplete_from,
title
} => <div key={name}>
<FieldName/>
<PopulateAtCheckboxes populate_at={data.populate_at} />
</div>);
我正在尝试遍历哈希中的所有键,但循环没有返回任何输出。 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()
没有 return 任何东西 - 使用 .map()
代替:
Object.keys(this.state.items).map(function (key) {
var item = this.state.items[key]
// ...
快捷方式是:
Object.values(this.state.items).map({
name,
populate_at,
same_as,
autocomplete_from,
title
} => <div key={name}>
<FieldName/>
<PopulateAtCheckboxes populate_at={data.populate_at} />
</div>);