gpt4 book ai didi

javascript - react js : Invariant Violation: processUpdates() when rendering a table with a different number of child rows

转载 作者:行者123 更新时间:2023-12-03 13:07:19 25 4
gpt4 key购买 nike

当我的 react 组件在点击事件后重新渲染时,出现以下错误:

Uncaught Error: Invariant Violation: processUpdates(): Unable to find child 2 of element. This probably means the DOM was unexpectedly mutated ...

仅当我的表的行数与之前呈现的版本不同时,才会发生这种情况。例如:

/** @jsx React.DOM */

React = require('react');

var _ = require("underscore");

var testComp = React.createClass({

getInitialState: function () {
return {
collapsed: false
};
},

handleCollapseClick: function(){
this.setState({collapsed: !this.state.collapsed});
},

render: function() {

var rows = [
<tr onClick={this.handleCollapseClick}><th>Header 1</th><th>Header 2</th><th>Header 3</th></tr>
];

if(!this.state.collapsed){
rows.push(<tr><th>Row1 1</th><th>Row1 2</th><th>Row1 3</th></tr>);
}

rows.push(<tr><th>Footer 1</th><th>Footer 2</th><th>Footer 3</th></tr>);

return <div>
<table>
{rows}
</table>
</div>
}

});

module.exports = testComp

如果我渲染不同的内容,但行数相同,我不会收到错误,因此如果我将 if 语句更新为:

if(!this.state.collapsed){
rows.push(<tr><th>Row1 1</th><th>Row1 2</th><th>Row1 3</th></tr>);
}else{
rows.push(<tr><th>Row2 1</th><th>Row2 2</th><th>Row2 3</th></tr>);
}

...一切正常。

在这种情况下,我是否需要强制 react 来重新渲染整个组件,而不仅仅是“更改”的元素?

最佳答案

您应该阅读完整的错误消息(至少我看到的是这样的):

Unable to find child 2 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 parent.

每张 table 都需要一个<tbody>元素。如果不存在,浏览器会添加它。但是,如果从外部操作 DOM,React 将无法工作。

相关:Removing row from table results in TypeError

关于javascript - react js : Invariant Violation: processUpdates() when rendering a table with a different number of child rows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26689900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com