如果状态为true播放youtube视频,而它为false,我想删除youtube播放。我的代码如下。
{this.state.isPreViewVideo && <PlayYouTube video_id="ScSn235gQx0" />}沙盒URL:
https://codesandbox.io/s/xryoz10k6o
再现方法:
如果输入表单中包含4位字符,setState将返回"isPreViewVideo: true“,如果该值小于false
当state为true时,它工作得很好,但当state为false时,我会遇到以下错误。
DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.有没有办法避免或解决这个错误?
发布于 2019-02-26 17:18:01
在playYouTube.tsx第78行中,将<React.Fragment>...</React.Fragment>替换为<div>...</div>
片段允许您对子节点列表进行分组,而无需向DOM中添加额外的节点。
这解释了错误Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
有关片段的更多信息,请单击此处https://reactjs.org/docs/fragments.html
发布于 2020-06-19 00:49:06
如果使用Google Translate (或任何其他更改页面DOM的插件),也会引发此错误Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node。
这在这期Github中有详细介绍:https://github.com/facebook/react/issues/11538
发布于 2020-11-10 19:56:18
问题说明:
当isPreViewVideo是真实的时,你会得到这样的结果:
<PlayYouTube video_id="ScSn235gQx0" />这可能会呈现如下所示的内容:
<div> <!-- the root element as rendered by PlayYouTube if isPreViewVideo is truthy -->
<embed /> <!-- the video player or whatever PlayYouTube renders -->
</div>现在,如果一些代码通过直接操作DOM和删除根div来删除播放器,那么您最终将得到...好吧,什么都没有。
但是在React的虚拟DOM中,根div仍然存在!因此,当isPreViewVideo出现错误时,React会尝试将其从真正的DOM中删除,但由于它已经消失,因此会抛出错误。
解决方案:
要使用这样的div扩展@henrik123的答案包装PlayYouTube ...
<div> <!-- the root element rendered if isPreViewVideo is truthy -->
<PlayYouTube video_id="ScSn235gQx0" />
</div>对此执行...causes以进行渲染:
<div> <!-- the root element rendered if isPreViewVideo is truthy -->
<div> <!-- the element as rendered by PlayYouTube -->
<embed /> <!-- the video player or whatever PlayYouTube renders -->
</div>
</div>现在,通过移除播放器的根div来移除播放器的相同代码使其如下所示:
<div> <!-- the root element rendered if isPreViewVideo is truthy -->
</div>现在,当isPreViewVideo变为falsy时,根既存在于React的虚拟DOM中,也存在于真实的DOM中,因此删除它没有问题。它的孩子已经改变了,但React在这种情况下并不关心-它只需要移除根。
备注:
除了div之外的其他HTML元素也可以使用。
注释2:
用React.Fragment而不是div包装是行不通的,因为React.Fragment不会向真正的DOM添加任何东西。所以用这个..。
<React.Fragment>
<PlayYouTube video_id="ScSn235gQx0" />
</React.Fragment>...you仍然以这样的方式结束:
<div> <!-- the root element as rendered by PlayYouTube if isPreViewVideo is truthy -->
<embed /> <!-- the video player or whatever PlayYouTube renders -->
</div>你也有同样的问题。
TL;灾难恢复解决方案:
用div包装PlayYouTube。
https://stackoverflow.com/questions/54880669
复制相似问题