Trying to get access to the component state from a getter, I noticed that this
is set to a different context than in a normal method and therefore this.state
doesn't work.
See here: http://jsfiddle.net/tkaby7ks/
Why is that and how can I get access to the state from a getter?
In React hooks, due to the way state is encapsulated in the functions of React. useState() , if a callback gets the state through React. useState() , it will be stale (the value when the callback was setup). But if it sets the state, it will have access to the latest state through the passed argument.
States can be used in Class Components, Functional components with the use of React Hooks (useState and other methods) while Props don't have this limitation.
State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
setState() setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
The point is that the getter is a property of the object you pass to React.createClass
, not of the class that is created: react treats it as a value. From reacts perspective, the following 2 code snippets are exactly the same:
var MyComponent = React.createClass({
foo: "asdf",
...
})
vs.
var MyComponent = React.createClass({
get foo() { return "asdf" },
...
})
For functions that you pass to createClass
, react binds the this
variable to the component, but for getters it is not possible.
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