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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29534224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:31:46  来源:igfitidea点击:

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

javascriptreactjsreact-jsx

提问by martins

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?

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

回答by Jonny Buchanan

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

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

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

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

回答by Olivier Pichou

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