I'm really sorry I'm posting this as it sounds crazy. I got a method to validate some inputs I have in a form inside a modal.
So I check on every this.state.variable and doing a push to an aux array to be then set to the original fieldErrors array.
But for some reason, when I check aux
before setting, length is 5. After setting to fieldErrors, i notice length is 0. What's going on?
Here's the code:
_validateMissingFields: function() {
var aux = [];
if (this.state.variable1.length === 0) {
aux.push('variable1');
}
if (this.state.variable2.length === 0) {
aux.push('variable2');
}
if (this.state.variable3.length === 0) {
aux.push('variable3');
}
if (this.state.variable4.length === 0) {
aux.push('variable4');
}
if (this.state.variable5.length === 0) {
aux.push('variable5');
}
console.log(aux.length) // -> shows 5
this.setState({ fieldErrors: aux });
}
Later on, when I do this.state.fieldErrors.length
after this method, shows 0.
By the way, this is how I'm initializing fieldErrors
:
getInitialState: function() {
return {
variable1: '',
variable2: '',
variable3: '',
variable4: '',
variable5: '',
fieldErrors: []
}
},
React setState is asynchronous which is why this.state cannot be read immediately.
See the docs for more info https://facebook.github.io/react/docs/react-component.html#setstate
setState is asynchronous, as has been mentioned a couple times, but it also accepts a callback function as a second parameter so if what you're trying to do with length can be done in a callback you can do something like
this.setState({ fieldErrors: aux }, () => {
console.log(this.state.fieldErrors.length); // Or whatever you're trying to do
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.