React JSX:迭代哈希并为每个键返回JSX元素 [英] React JSX: Iterating through a hash and returning JSX elements for each key

查看:80
本文介绍了React JSX:迭代哈希并为每个键返回JSX元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历散列中的所有键,但是没有从循环返回输出。 console.log()按预期输出。知道为什么JSX没有返回并输出正确吗?

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


推荐答案

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

Array.prototype.forEach()不返回任何内容 - 请改用 .map()

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

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

这篇关于React JSX:迭代哈希并为每个键返回JSX元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆