反应“遇到无效的孩子”错误

时间:2015-01-09 21:09:11

标签: javascript reactjs

我使用react来呈现一个类似于电子表格的表格。每个单元格都有一个输入字段,您可以在一行中填充每个单元格。但是,我只希望在任何时候都有一行空输入。我使用以下代码呈现<tbody>

var existing_rows_length = this.state.existing_rows.length
  , new_index = existing_rows_length + this.state.new_rows.length - 1

var existing_rows = this.state.existing_rows.map(function(row, i) {
  return (
    <TableRow data={row} key={"row-" + i} index={i} />
  )
})

var new_rows = this.state.new_line_items.map(function(row, i) {
  return (
    <TableRow data={li} key={"row-" + i + existing_row_length} index={i + existing_row_length} unsaved={true} />
  )
})

return (
  <tbody>
    {existing_rows}
    {new_line_items}
    <TableRow data={{}} index={new_index} unsaved={true} />
  </tbody>
)

然后,在字段的每个输入上,它序列化输入,并将它们设置为&#34; new_rows&#34;

var new_rows = $(this.getDOMNode())
  .find('[data-unsaved][data-has-changed]')
  .map(function(i, el) { return $(el).find('input') })
  .map(function(i, inputs) {
    return _.reduce(inputs, function(memo, input) {
      var $input = $(input)
        , attrName = $input.attr('name').match(/\[([^\[]*)\]$/)[1]
      memo[attrName] = $input.val()
      return memo
      }, {})
  })

this.setState({ // This is line 17, in the function ensureNewRow, of table_body.js
  existing_rows: this.state.existing_rows
, new_rows: new_rows
})

我的逻辑是,一旦你开始在新行中填写输入,那么它将在state.new_rows中保存它并在其下面渲染出另一个空行。但是,它会停止渲染并给出以下错误:

[Warning] Child objects should have non-numeric keys so ordering is preserved. Check the render method of LineItemList. See http://fb.me/react-warning-keys for more information. (851543_741761425909553_1789649762_n.js, line 9663)
[Error] Error: Invariant Violation: traverseAllChildren(...): Encountered an invalid child; DOM elements are not valid children of React components.
  perform (851543_741761425909553_1789649762_n.js, line 15428)
  batchedUpdates (851543_741761425909553_1789649762_n.js, line 8681)
  enqueueUpdate (851543_741761425909553_1789649762_n.js, line 13744)
  replaceState (851543_741761425909553_1789649762_n.js, line 6211)
  setState (851543_741761425909553_1789649762_n.js, line 6183)
  ensureNewRow (table_body.js, line 17)
  (anonymous function) ([native code], line 0)
  dispatch (jquery.js, line 4642)
  handle (jquery.js, line 4310)

以下链接实际上将我带到了这里:&#34; http://facebook.github.io/react/docs/multiple-components.html#dynamic-children&#34;它表示用字符串前置键(我已经完成了 - 我尝试使用相同的前缀为它们添加前缀,并尝试使用不同的前缀)。

对不起,代码太漂亮了,我已经被困在这个问题好几天了!如果有人能够至少指出我正确的方向,或让我知道可能导致问题的原因,那将是非常有帮助的!或者,如果我违反某些React原则,请告诉我它是什么,以便我可以修复它(这是我第一次使用React)

1 个答案:

答案 0 :(得分:0)

问题来自于意外将查询对象保存到状态。这导致变量在map函数中翻转,将键设置为[object Object]并将<TableRow>保留为仅给定整数的渲染。我刚刚在.toArray()任务链的末尾调用了new_rows,它确实有效!