Trying to build a React experiment. I am facing the problem of inaccessible Class.state. The whole code in my CodePen pen: https://codepen.io/Godje/pen/JNQVad
On line 115 you can see me binding this to the method:
this.generateQuestion = this.generateQuestion.bind(this);
On line 200 and 201 I am checking if this refers to the App class, not to the function scope. AND IT DOES, BUT not on the this.state.
console.log(this); //success. Return App object, which HAS "state" key
console.log(this.state); //undefined. Even though, It refers
//to the object that has a "state" key
//it doesn't return it for some reason.
I need that state to be accessible. What is the problem?
You have written following code in constructor:
this.state = {
gameState: {
state: "intro",
quest: this.generateQuestion(),
score: 0,
round: 0,
time: 3
}
}
generateQuestion will be called first and after its execution initial state i.e this.state will be set in the component, that's why you are getting it undefined.
You're doing too much binding. I fixed and forked your code ONLY pertaining to the GenerateQuestion function in this forked CodePen. Normally I would add the code snippet, but with how this is all bound together, I'll just address the concept.
In React, you bind all your functions just as you did in the constructor - with this.exampleFunction = this.exampleFunction.bind(this);. From here, you maintain your state by using React's build in setState function (read about it more in the documentation here).
Do not set state by direct definition as you are throughout your code (ex. this.state.gameState.score = 0;. And when using setstate, keep in mind that any objects defined int he state will be updates as a whole object (also discussed in the linked documentation).
Most importantly, you lost your bindings when you rebing the functions as you do starting at line 110 and a few other places. This is what was keeping you from accessing the state. You'll notice that I got rid of the additional bindings on generateQuestion to get it to work.
Set variables to hold a result you need to act on, such as let answer = this.handleAnswer();. Then set anything you need to keep for render purposes to the component state. You can save additional non-render information to the class without worrying about binding like this: this.additionalAttribute = 'string-in-this-case';. These additional attributes will not trigger update events - keep that in mind.
Focusing on setting all state following React's recommended setState function. And stop rebinding functions to themselves outside of the constructor. Use variables, additional attribute assignments, and most importantly - more state as needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With