6

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

5
  • Can you be sure, that there is only a single instance of component A? If yes, then assigning this to a static variable seems reasonable. If not, then then you need to rethink the question. Commented Feb 21, 2017 at 17:08
  • I'm not sure if static functions need bind to keep the context. You could give it a try Commented Feb 21, 2017 at 17:09
  • static functions will never have access to the this your non static functions have access to. Think about non-static methods, as each instance have it, and think about static methods as the class has it. Commented Feb 21, 2017 at 17:10
  • yes i am sure it will be one instance. Commented Feb 21, 2017 at 17:10
  • i tried to bind the static func but noway it give me an erro Commented Feb 21, 2017 at 17:10

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

is defining a global var self = this a bad idea than ? it will be no more than one instance of A . thanks :)
you can use the global variable, but i think it will be better to use some architecture like redux/flux you can easily do this kind of task. Lets say from any component you want to change something in A, pass the value to store the listen the changes in comp A. it will be a more proper way :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.