React JSX:迭代哈希并为每个键返回JSX元素

mar*_*ins 53 javascript reactjs react-jsx

我正在尝试迭代哈希中的所有键,但是没有从循环返回输出.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>
    );
  }
Run Code Online (Sandbox Code Playgroud)

Jon*_*nan 109

Object.keys(this.state.items).forEach(function (key) {
Run Code Online (Sandbox Code Playgroud)

Array.prototype.forEach()不返回任何东西 - .map()改为使用:

Object.keys(this.state.items).map(function (key) {
  var item = this.state.items[key]
  // ...
Run Code Online (Sandbox Code Playgroud)

  • 如果你的对象在第一次渲染**中引用了'undefined'或'null'的道具,你将得到**错误**.使用"Object.keys(this.props.items**|| {}**).map(...)"解决它. (6认同)

Oli*_*hou 5

快捷方式是:

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>);
Run Code Online (Sandbox Code Playgroud)