I am struggling to toggle a Boolean
state from true to false when the result is undefined
. I have tried a lot but didn't work.
The boolean state in constructor is defined as follows :
class UserInfo extends Component{
constructor(props){
super(props);
this.state = {
token : '',
isVisible : true,
};
}
This function should check if token
holds a value or undefined
and then continue to execute the right condition accordingly. However, when token
is undefined
the isVisible
is not getting toggled to false and it will remain true no matter what.
Any suggestions I would be much appreciated.
ToggleFunction = (token) => {
if (this.state.token === undefined){
this.setState({
isVisible: !this.state.isVisible,
});
}
else {
this.setState(state => ({
isVisible: state.isVisible
}));
}
};
In your ToggleFunction, you're checking this.state.token === undefined
as opposed to token === undefined
from the parameter of the method call.
Try:
ToggleFunction = (token) => {
if (token === undefined){
this.setState({
isVisible: !this.state.isVisible,
});
}
else {
this.setState(state => ({
isVisible: state.isVisible
}));
}
};
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.