koo*_*osa 21 javascript reactjs
在click事件后重新呈现我的react组件时,我收到以下错误:
Uncaught Error: Invariant Violation: processUpdates(): Unable to find child 2 of element. This probably means the DOM was unexpectedly mutated ...
Run Code Online (Sandbox Code Playgroud)
仅当我的表具有与先前呈现的版本不同的行数时才会发生这种情况.例如:
/** @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
Run Code Online (Sandbox Code Playgroud)
如果我呈现不同的内容,但行数相同,我不会得到错误,所以如果我将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>);
}
Run Code Online (Sandbox Code Playgroud)
一切正常
在这种情况下,我是否需要强制反应来重新渲染整个组件,而不仅仅是"已更改"的元素?
Fel*_*ing 33
您应该阅读完整的错误消息(至少这是我所看到的):
无法找到元素的子元素2.这可能意味着该DOM意外突变(例如,由浏览器),通常由于忘记一个
<tbody>使用时表,嵌套标签等<form>,<p>或<a>,或使用在母非SVG元素.
每个表都需要一个<tbody>元素.如果它不存在,浏览器将添加它.但是,如果从外部操作DOM,则React不起作用.
我在处理p标签时遇到过这种情况.我在段落中嵌套了段落.
要解决此问题,我更换了包装p与元素的div元素.
之前:
render: function render() {
return (
<p>
<p>1</p>
<p>2</p>
</p>
);
}
Run Code Online (Sandbox Code Playgroud)
后:
render: function render() {
return (
<div>
<p>1</p>
<p>2</p>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)