Callback In Nested State Object
Solution 1:
You need to change handleChange
declaration:
classAppextendsReact.Component {
...
handleChange = (e) => {
this.setState({ properties[e.target.name]: e.target.value })
}
...
}
When you write handleChange = (e) => {...}
it will bind as pointed out by @Li357, it doesn't not bind at all, on the contrary it creates a property of the class that is an arrow function that doesn't bind this
pointer of the function to your component so that you will be able to access setState
this
, capturing the this
value of the surrounding scope, the class.
Update:
It has been pointed out that using arrow functions as class properties is an experimental feature, so it is safer to use this.handleChange = this.handleChange.bind(this)
in constructor
of the component.
I got the example working with this code:
handleChange(event) {
const target = event.target;
this.setState((prevState) => ({
properties: {...prevState.properties, ...{ [target.name]: target.value } }
})
);
}
I am not entirely sure why it behaves the way it does, I am guessing it has to do with the fact that setState
is async and react
wraps events in its own SyntheticEvent
which will be reused and all properties will be nullified after the event callback has been invoked
(see react docs). So if you store the original reference to target
outside of setState
it will get scoped and used inside setState
.
Here is a working example on codesandbox.
Update 2:
According to react docs, one can't access react SyntheticEvent
in an asynchronous way. One way of dealing with this would to be call event.persist()
which will remove the wrapper, but this might not be a good idea since SyntheticEvent
is a cross-browser wrapper around the browser’s native event which makes sure the events work identically across all browsers.
Post a Comment for "Callback In Nested State Object"