【问题标题】:ReactJS Dynamically hiding and showing table column causes Invariant ViolationReactJS 动态隐藏和显示表格列导致 Invariant Violation
【发布时间】:2015-01-04 18:12:33
【问题描述】:

我有一个表格的 React 组件。如果用户不是我,那么当我看到该用户的个人资料页面时,我只会看到表格的前三列。如果用户是我,那么我会看到四列。但是,动态更改列会导致以下错误:

Uncaught Error: Invariant Violation: processUpdates(): Unable to find child 3 of element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `.0.1.1.0.0.1.0.0`.

我环顾四周,确保我的桌子是用 .我怎样才能在 React 中允许这个表的灵活性?

我的表壳看起来像这样:

var CategoriesTable = React.createClass({
  render: function() {
    var includeReps = false;
    var repsHeader = '';
    if (this.props.currentUser.username === this.props.user.username) {
      includeReps = true;
      repsHeader = <th>Reps</th>;
    }

  return (
    <div className="categoriesTable panel panel-default">
      <CategoriesHeader user={this.props.user} />
      <table className="table table-bordered table-striped">
        <tbody>
          <tr>
            <th>Category</th>
            <th>Direct Rep</th>
            <th>Crowd Rep</th>
            {repsHeader}
          </tr>
          {this.props.user.categories.map(function(category) {
            return <CategoriesItem key={category.id} category={category.name} directRep={category.directScore} prevDirectRep={category.previousDirectScore} crowdRep={category.crowdScore} reps={category.reps} includeReps={includeReps} />;
          })}
        </tbody>
      </table>
    </div>
  );
}
});

每个表格行如下所示:

var CategoriesItem = React.createClass({
  render: function() {
    var reps = this.props.includeReps ? <td>{this.props.reps}</td> : '';

    return (
      <tr className="categoriesItem">
        <td>{this.props.category}</td>
        <td><ScoreBar directRep={this.props.directRep} prevDirectRep={this.props.prevDirectRep} category={this.props.category}/></td>
        <td>{this.props.crowdRep}</td>
        {reps}
      </tr>
    );
  }
});

为什么我可以让 React 接受这些表更改?当我从包含所有四列的表格开始,然后切换到不同用户的个人资料页面时,第四个表格数据块变成了

【问题讨论】:

    标签: html reactjs


    【解决方案1】:

    也许是个 hack,但是给 react 组件一个 key 会在 key 改变时强制整个组件重新渲染。如果每个配置文件页面都为表格提供了一个唯一的键,那么这个问题就会消失。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多