Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why getters don't have access to state in React components?

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?

like image 527
vdg Avatar asked Dec 12 '14 09:12

vdg


People also ask

How do you access state in React hooks?

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.

Which component can have states in React?

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.

Can we set state as props in React?

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.

Can you set a React component as 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.


1 Answers

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.

like image 107
OlliM Avatar answered Sep 30 '22 04:09

OlliM