this are my initial state:
this.state = {
requiredError: false,
addressSelectError: false,
recipientError: false,
open: false,
};
and this is where my problem is:
processCheckout () {
this.setState({
requiredError: true,
addressSelectError: true,
recipientError: true,
}, () => {
console.log('required error', requiredError);
console.log('address error', addressSelectError);
console.log('recipient error', recipientError);
})
}
I have set them all to true
but the console still logs false:
I have used the callback but it still does not change. any help?
I am calling the processCheckout()
function on onClick()
of a button.
EDIT: I have tried console logging in render, and all of them are true
Change your function to an arrow syntax so it has access to the global state.
processCheckout= () => {
this.setState({
requiredError: true,
addressSelectError: true,
recipientError: true,
}, () => {
console.log('required error', this.state.requiredError);
console.log('address error', this.state.addressSelectError);
console.log('recipient error', this.state.recipientError);
})
Or bind it at the constructor like
constructor(props) {
super(props);
// This binding is necessary to make `this` work
this.processCheckout = this.processCheckout.bind(this);
}
You can read more about it here
Without seeing the entire code I assume you've declared the variables requiredError, addressSelectError and recipientError
somewhere in your class:
In the callback, try to access this.state directly
processCheckout() {
this.setState(
{
requiredError: true,
addressSelectError: true,
recipientError: true
},
() => {
console.log("required error", this.state.requiredError);
console.log("address error", this.state.addressSelectError);
console.log("recipient error", this.state.recipientError);
}
);
}
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.