Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native : Access Component state inside a static function

I have a component defined like this

export class A extends Component{
   constructor(props){
     this.state = {
        scene:0
     }
   }
  static changeScene(scene){
     this.setState({scene:scene})
  }
}

I want to call change scene from anywhere using A.changeScene(sceneVal) to change the scene in A. the problem is i can't access this.setState i got this error Unhandled JS Exception: this.setState is not a function.

I am sure that the A component is already mounted. I can bypass this error by defining a global variable var self = null; and inside the constructor self = this in the constructor but i want a better way to rosolve this problem

like image 983
LHIOUI Avatar asked Nov 08 '22 01:11

LHIOUI


1 Answers

Reason is, if you use static function then a static method won't be able to access this inside that function. You should avoid using static function. Static methods have no access to the values, properties, and methods defined on an instance of the class using this.

Check this article: http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx

like image 75
Mayank Shukla Avatar answered Nov 14 '22 22:11

Mayank Shukla