redux ReactJS -未捕获NotFoundError:无法在“节点”上执行“insertBefore”:

5lwkijsr  于 2022-11-24  发布在  React
关注(0)|答案(3)|浏览(262)

我有一个div,其中附加了另外三个div,如下所示。状态值是通过循环componentWillReceiveProps()的api的结果来设置的。但是我遇到了一个错误问题
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结果为空,则获取
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>
    )
}
6yt4nkrj

6yt4nkrj1#

当用户使用Google Translate时,有时会发生这种情况,它会改变文本节点,并且React会在下次渲染时中断。更多信息以及如何修复:https://github.com/facebook/react/issues/11538#issuecomment-390386520
您还可以将以下属性添加到HTML标记中,以禁用Google Translate并解决此问题:
<html class="notranslate" translate="no">

afdcj2ne

afdcj2ne2#

我认为这是失败的,因为你是渲染方法之外的渲染。我也有这个问题,这是因为我在我的渲染方法中有如下代码:

<div id="myContent">
  {this.getMyContentFromAChildClass()}
</div>

然后在课堂的其他地方,我使用第三方库SimpleBar,使用JQuery向div添加滚动条,如下所示:

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

SimpleBar在混合中添加了它自己的div,当React试图呈现{this.getMyContentFromAChildClass()时,它混淆了在哪里添加它,我得到了上面的错误消息。
修复方法是不直接修改父div:

<div id="myContent">
  <div id="addingThisExtraDivIsTheFix">  <-- Add This
    {this.getMyContentFromAChildClass()}
  </div>
</div>
7vux5j2d

7vux5j2d3#

上面的解决方案对我不起作用。
在React中,一个改变的key是一个重新呈现组件的指示,这也是OP在本例中想要的。
将具有className='div1'的父项div变更为下列内容:

<div className="div1" key={JSON.stringify(nextProps)}>

相关问题