React JS - 未捕获的 NotFoundError:无法在“节点”上执行“insertBefore”:

Har*_*esh 7 javascript reactjs redux

我有一个divwhere 里面的另外三个divs 附加如下。状态值是通过循环来自 api 的结果来设置的componentWillReceiveProps()。但我正面临一个错误问题

Uncaught NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node

如果 api 结果为 null 得到

Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

我怎样才能解决这个问题?

componentWillReceiveProps(nextProps) {
    var sub1 = [], sub2 = [], sub3 = [];
    if(result) {
        result.sub1.map((item, index) => {
            sub1.push(
                <div>
                    <p>{item.name}</p>
                </div>
            )
        })
        result.sub2.map((item, index) => {
            sub2.push(
                <div>
                    <p>{item.name}</p>
                </div>
            )
        })
        result.sub3.map((item, index) => {
            sub3.push(
                <div>
                    <p>{item.name}</p>
                </div>
            )
        })

        this.setState({ subDiv1:sub1, subDiv2:sub2, subDiv3:sub3 })
    }
}

render() {
    return(
        <div className="row top_bar">
            <div className="search left col-xs-5 col-sm-4 col-md-5 col-lg-6">
                <form>
                    <input type="text" id="search_box" name="search_box" placeholder="Search" onKeyUp={this.keyUpFn} />
                </form>
                <div className="div1">
                    { this.state.subDiv1 }
                    { this.state.subDiv2 }
                    { this.state.subDiv3 }
                </div>
            </div>
            <div className="top_right col-xs-7 col-sm-8 col-md-7 col-lg-6">
                <div className="top_outer">
                </div>
            </div>
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*ton 8

我相信这是失败的,因为您正在渲染方法之外进行渲染。我也遇到了这个问题,这是因为我的渲染方法中有如下代码:

<div id="myContent">
  {this.getMyContentFromAChildClass()}
</div>
Run Code Online (Sandbox Code Playgroud)

然后在课堂上的其他地方,我使用了一个 3rd 方库 SimpleBar,使用 JQuery 向 div 添加滚动条,如下所示:

const myContentElement = $("#myContent")[0];
if (!this.scrollbar && myContentElement) {
  this.scrollbar = new SimpleBar(myContentElement, {autoHide: false});
}
Run Code Online (Sandbox Code Playgroud)

SimpleBar 在混合中添加了它自己的 div,当 React 尝试渲染{this.getMyContentFromAChildClass()它时,它混淆了在哪里添加它,我收到了上述错误消息。

解决方法是不直接修改父 div:

<div id="myContent">
  <div id="addingThisExtraDivIsTheFix">  <-- Add This
    {this.getMyContentFromAChildClass()}
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 您是这个答案的传奇人物,已经尝试解决这个问题几个小时了,但在父级内部添加了一个额外的容器,我的代码现在可以工作了:) (4认同)

Ale*_*der 6

有时当用户使用谷歌翻译时会发生这种情况,它会改变文本节点,而 React 在下一次渲染时会中断。更多信息以及如何修复它:https : //github.com/facebook/react/issues/11538#issuecomment-390386520

您还可以将下一个属性添加到 HTML 标记以禁用 Google 翻译并解决此问题:

<html class="notranslate" translate="no">