React JSX: Iterating through a hash and returning JSX elements for each key

主宰稳场 提交于 2019-12-18 12:44:39

问题


I'm trying to iterate through all the keys in a hash, but no output is returned from the loop. console.log() outputs as expected. Any idea why the JSX isn't returned and outputted correct?

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

回答1:


Object.keys(this.state.items).forEach(function (key) {

Array.prototype.forEach() doesn't return anything - use .map() instead:

Object.keys(this.state.items).map(function (key) {
  var item = this.state.items[key]
  // ...



回答2:


a shortcut would be:

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


来源:https://stackoverflow.com/questions/29534224/react-jsx-iterating-through-a-hash-and-returning-jsx-elements-for-each-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!