StructureBuilder / react-keep-alive

A component that maintains component state and avoids repeated re-rendering.
MIT License
980 stars 105 forks source link

清除某个路由缓存后 再打开Cannot read property 'replaceChild' of undefined #73

Closed fzh199410 closed 4 years ago

fzh199410 commented 4 years ago

你好,我这边是用mobx控制Provider的includes的, 其他都没问题,就是当清除掉缓存页面的前一个缓存页面,然后再去加载缓存, 就会报错。 具体步骤

  1. 删除关于孩子缓存 image

2.再次路由到关于孩子 报错 image

麻烦帮忙推理下是什么地方出问题了呢 感谢

fzh199410 commented 4 years ago

问题初步解决了 fork到了内部自用,大概讲下 1:当时根据报错找到了一个相关的issue [https://github.com/facebook/react/issues/11538](Make React resilient to DOM mutations from Google Translate), gaearon大神提供了一个辅助解决方案

if (typeof Node === 'function' && Node.prototype) {
  const originalRemoveChild = Node.prototype.removeChild;
  Node.prototype.removeChild = function(child) {
    if (child.parentNode !== this) {
      if (console) {
        console.error('Cannot remove a child from a different parent', child, this);
      }
      return child;
    }
    return originalRemoveChild.apply(this, arguments);
  }

  const originalInsertBefore = Node.prototype.insertBefore;
  Node.prototype.insertBefore = function(newNode, referenceNode) {
    if (referenceNode && referenceNode.parentNode !== this) {
      if (console) {
        console.error('Cannot insert before a reference node from a different parent', referenceNode, this);
      }
      return newNode;
    }
    return originalInsertBefore.apply(this, arguments);
  }
}

2 按我的理解(可能并非作者本意),include的改变应该会响应到KeepAliveProvider的cache和keys里面,所以我就在componentWillReceiveProps里面监听include的减少行为发生,并执行delCache删除cache 和 keys里的缓存 效果图如下 image