How to check if a component is mounted in React-Native ES6

后端 未结 2 1203
终归单人心
终归单人心 2021-02-11 22:08

I am setting a listener in my application and using force update whenever it is broadcasted but it gives error forceUpdate cant be called on unmounted component. How can I check

相关标签:
2条回答
  • 2021-02-11 22:50

    Using ReactUpdateQueue, you can avoid managing your own isMounted state.

    const ReactUpdateQueue = require('ReactUpdateQueue');
    
    // Pass the ref to your component.
    if (ReactUpdateQueue.isMounted(view)) {
      // Your component is mounted!
    }
    
    0 讨论(0)
  • 2021-02-11 23:05

    You can handle this yourself in your component:

    componentDidMount() { 
      this._mounted = true;
    }
    
    componentWillUnmount() {
      this._mounted = false;
    }
    

    Then you can check the value of this._mounted in your listener.

    Please note that using forceUpdate() should be avoided https://facebook.github.io/react/docs/component-api.html#forceupdate

    Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). This makes your component "pure" and your application much simpler and more efficient.

    0 讨论(0)
提交回复
热议问题