【问题标题】:React JSX: Iterating through a hash and returning JSX elements for each keyReact JSX:遍历哈希并为每个键返回 JSX 元素
【发布时间】:2015-06-14 13:35:50
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs react-jsx


    【解决方案1】:

    快捷方式是:

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

    【讨论】:

      【解决方案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]
        // ...
      

      【讨论】:

      • 是的,我用map 替换了forEach,它成功了。谢谢! :-)
      • var item = this.state.item[key]。 this和你想的不一样,需要使用var that=this,and that.state.item[key]
      • this 作为第二个参数传递,它在调用函数时设置this 的适当值。
      • 如果你的对象在第一次渲染时引用了一个“未定义”或“空”的道具,你会得到一个错误。使用 "Object.keys(this.props.items || {}).map(...)" 解决它。
      • 哇!谢谢@MadeInMoon,当它抛出错误'null不是对象(评估'Object.keys'再次感谢:)时,我不知道如何在我的mapStateToProps中解决这个问题:)
      猜你喜欢
      • 1970-01-01
      • 2021-03-25
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 2013-08-20
      • 2016-08-19
      相关资源
      最近更新 更多