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

后端 未结 2 1202
终归单人心
终归单人心 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 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.

提交回复
热议问题