【问题标题】:How to toggle a Boolean in react native?如何在本机反应中切换布尔值?
【发布时间】:2020-03-14 16:05:11
【问题描述】:

当结果为undefined 时,我正在努力将Boolean 状态从真切换为假。我已经尝试了很多但没有奏效。

构造函数中的布尔状态定义如下:

class UserInfo extends Component{
constructor(props){
    super(props);
    this.state = {
    token : '',
    isVisible : true,
   };
}

这个函数应该检查token 是否持有一个值或undefined,然后相应地继续执行正确的条件。但是,当 tokenundefined 时,isVisible 不会切换为 false,无论如何它都将保持为 true。

如有任何建议,我将不胜感激。

 ToggleFunction = (token) => {
    if (this.state.token === undefined){
      this.setState({
        isVisible: !this.state.isVisible,
        });   
  }
  else {
    this.setState(state => ({

      isVisible: state.isVisible


    }));
  }
};

【问题讨论】:

  • 为什么这个问题被否决了?
  • 在您声明类的示例中,类没有右括号。这只是问题中的一个错字吗?
  • 这是一个错字,这不是问题,但谢谢
  • 几件事,因为我不知道您的应用程序的上下文:A)从未使用过token,而是使用state.token。这是故意的吗? B) 如果state.token === undefined,则state.isVisible 设置为state.isVisible 的反面。在您的描述中,您说它应该始终设置为 false
  • 你说得对,我使用的是this.state.token 而不是token,导致跳过if 条件并始终执行else。感谢您的关注

标签: javascript reactjs react-native boolean


【解决方案1】:

在您的 ToggleFunction 中,您从方法调用的参数中检查 this.state.token === undefined 而不是 token === undefined

试试:

ToggleFunction = (token) => {
    if (token === undefined){
      this.setState({
        isVisible: !this.state.isVisible,
        });   
  }
  else {
    this.setState(state => ({
      isVisible: state.isVisible
    }));
  }
};

【讨论】:

    猜你喜欢
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多