React JSX:遍历哈希并为每个键返回 JSX 元素

IT技术 javascript reactjs react-jsx
2021-04-29 06:39:44

我正在尝试遍历散列中的所有键,但没有从循环返回任何输出。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>
    );
  }
2个回答
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]
  // ...

一个快捷方式是:

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>);