有没有办法检查React组件是否已卸下?

JavaScript React.js

十三Itachi

2020-03-18

我有一个用例,需要卸载我的react组件。但是在某些情况下,特定的反应组件会通过不同的功能卸载。因此,我需要在卸载之前检查组件是否已安装。

第2167篇《有没有办法检查React组件是否已卸下?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
Mandy猿理查德 2020.03.18

您可以使用:

myComponent.updater.isMounted(myComponent)

“ myComponent”是您的react组件的实例。如果安装了组件,则将返回“ true”,否则将返回“ false”。

  • 这是不支持的方式来做到这一点。您最好取消订阅componentWillUnmount上的所有异步/事件
蛋蛋宝儿 2020.03.18

我发现该组件将被卸载,生成填充此变量

if(!this._calledComponentWillUnmount)this.setState({vars});

十三Sam 2020.03.18

如果您使用钩子:

function MyComponent(props: Props) {
  const [isMounted, setIsMounted] = useState<boolean>(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  useEffect(() => {
    return () => {
      setIsMounted(false);
    }
  }, []);

  return (...);
}

export default MyComponent;
null 2020.03.18

使用@DerekSoike答案,但是在我的情况下,useState用于控制挂载状态不起作用,因为该状态在不必

对我有用的是使用单个变量

myFunct是在中调用的setTimeout,而我的猜测是,当同一组件在另一个页面中初始化钩子时,它会恢复该状态,从而导致内存泄漏再次出现

所以这对我不起作用

  const [isMounted, setIsMounted] = useState(false)

  useEffect(() => {
    setIsMounted(true)
    return () => setIsMounted(false)
  }, [])

  const myFunct = () => {
    console.log(isMounted) // not always false
    if (!isMounted) return
    // change a state
  }

这确实为我工作

  let stillMounted = { value: false }
  useEffect(() => {
    stillMounted.value = true
    return () => (stillMounted.value = false)
  }, [])

  const myFunct = () => {
    if (!stillMounted.value) return
    // change a state
  }
神奇猴子米亚 2020.03.18

我到达这里是因为我正在寻找一种停止pollingAPI的方法。

反应文档不覆盖websocket的情况下,但不是轮询之一。

我的解决方法

// React component

React.createClass({
    poll () {
        if (this.unmounted) {
            return
        }
        // otherwise, call the api
    }
    componentWillUnmount () {
        this.unmounted = true
    }
})

有用。希望能帮助到你

请让我知道你们是否知道任何失败的测试案例=]

猴子L 2020.03.18

另一个解决方案是使用Refs如果您使用的是React 16.3+,请在render函数中对顶级项目进行引用。

然后只需检查ref.current是否为null。

例:

class MyClass extends React.Component {
  constructor(props) {
    super(props);
    this.elementRef = React.createRef();
  }

  checkIfMounted() {
     return this.elementRef.current != null;
  }

  render() {
    return (
      <div ref={this.elementRef} />
    );
  }
}
梅Harry米亚 2020.03.18

由于isMounted()已正式弃用,因此您可以在组件中执行以下操作:

componentDidMount() { 
  this._ismounted = true;
}

componentWillUnmount() {
   this._ismounted = false;
}

state在ReactJS文档中详细介绍了这种维护自己的变量的模式isMounted是一个Antipattern

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android