拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 reactjs组件中if(x)和if(x==true)的区别

reactjs组件中if(x)和if(x==true)的区别

白鹭 - 2022-01-26 2123 0 0

下面我在写ReactJs代码的时候,第一次使用if(this.state.username==true),没有得到预期的结果。但是当我使用if(this.state.username)它时,它可以按我的需要作业。因此,我可以明显地看到if(x==true)之间存在差异if(x)我也知道有时,它们可能意味着相同并产生相同的结果。我的问题是,如果我的建构式设定如下,为什么这两个表达式的行为会不同。这里的真正含义是if(this.state.username)什么?谢谢你帮我理解。

  constructor(props){
    super(props)
    this.state = {username:""}
  }

两段代码如下:

class MyForm extends React.Component {
  constructor(props){
    super(props)
    this.state = {username:""}
  }
  changeName = (e) =>{
    let target = e.target;
    let name   = target.name; 
      let value  = target.value;
    this.setState ({[name]: value});
  }
  render(){
    let myHeader;
    if(this.state.username==true){
        myHeader = <h1>Hello {this.state.username}</h1>;
    }else{
        myHeader = "";
    }
    return (
      <form>
        {myHeader}
        <h1>{this.state.username}</h1>
        <p>Enter your name:</p>
        <input
          name='username'
          type="text"
          onChange = {this.changeName}
        />
      </form>
    );
  }
}   
ReactDOM.render(<MyForm />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>


<div id="root"></div>

class MyForm extends React.Component {
  constructor(props){
    super(props)
    this.state = {username:""}
  }
  changeName = (e) =>{
    let target = e.target;
    let name   = target.name; 
      let value  = target.value;
    this.setState ({[name]: value});
  }
  render(){
    let myHeader;
    if(this.state.username){
        myHeader = <h1>Hello {this.state.username}</h1>;
    }else{
        myHeader = "";
    }
    return (
      <form>
        {myHeader}
        <h1>{this.state.username}</h1>
        <p>Enter your name:</p>
        <input
          name='username'
          type="text"
          onChange = {this.changeName}
        />
      </form>
    );
  }
}   
ReactDOM.render(<MyForm />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>


<div id="root"></div>

uj5u.com热心网友回复:

if (expr)将被视为true如果expr“truthy”

'<str>' == truetrue如果<str>等于,将考虑表达式'1'

在你的情况下,这样做可能更有意义

if (this.state.username !== '') {

参考:

  • https://tc39.es/ecma262/#sec-equality-operators
  • https://tc39.es/ecma262/#sec-islooselyequal

uj5u.com热心网友回复:

使用if(this.state.username==true)之间有区别if(this.state.username)使用前者比较this.state.usernamewith的值true,这当然是假的,除非它回传一个字符串值1,在这种情况下它会回传true
但是,执行后者会强制转换this.state.username为 boolean 并检查是否this.state.username有值(例如 not undefined)。
因此,如果您想使用if(this.state.username==true),则必须this.state.username首先使用!!(或Boolean强制转换为布林值

if(!!this.state.username==true) {
  // your code goes here
}

uj5u.com热心网友回复:

哈哈,太搞笑了。我已经尝试过所有的真伪。让我们看看结果:

console.log('Truthies:')
console.log('"a" == true           returns:', "a" == true)
console.log('"1" == true           returns:', "1" == true)
console.log('1 == true             returns:', 1 == true)
console.log('3 == true             returns:', 3 == true)
console.log('-1 == true            returns:', -1 == true)
console.log('[] == true            returns:', [] == true)
console.log('{} == true            returns:', {} == true)
console.log('function a(){return true} == true    returns:', function
a(){return true} == true)
console.log('"true" == true        returns:', "true" == true)

console.log('')
console.log('Falsies:')
console.log('NaN == false          returns:', NaN == false)
console.log('"" == false           returns:', "" == false)
console.log('`` == false           returns:', `` == false)
console.log('0 == false            returns:', 0 == false)
console.log('undefined == false    returns:', undefined == false)
console.log('null == false         returns:', null == false)


console.log('')
console.log('Truthies not-equal false:')
console.log('"a" !== false           returns:', "a" !== false)
console.log('1 !== false             returns:', 1 !== false)
console.log('"1" !== false           returns:', "1" !== false)
console.log('3 !== false             returns:', 3 !== false)
console.log('-1 !== false            returns:', -1 !== false)
console.log('[] !== false            returns:', [] !== false)
console.log('{} !== false            returns:', {} !== false)
console.log('function a(){return true} !== false     returns:', function
a(){return true} !== false)
console.log('"true" !== false         returns:', "true" !== false)

console.log('')
console.log('Truthies not-equal true:')
console.log('"a" !== true           returns:', "a" !== true)
console.log('1 !== true             returns:', 1 !== true)
console.log('"1" !== true           returns:', "1" !== true)
console.log('3 !== true             returns:', 3 !== true)
console.log('-1 !== true            returns:', -1 !== true)
console.log('[] !== true            returns:', [] !== true)
console.log('{} !== true            returns:', {} !== true)
console.log('function a(){return true} !== true     returns:', function
a(){return true} !== false)
console.log('"true" !== true         returns:', "true" !== true)

有一些棘手的事情。比如他们1 == true1 !== truetrue??。

无论如何......你最好使用!!以保持安全:

const { useState } = React

const MyForm = () => {
  const [state, setState] = useState({ username: '' })

  const handleChange = ({ target: { name, value } }) => {
    setState({ [name]: value })
  }
  
  return (
    <form>
      {!!state.username && (
        <h1>Hello {state.username}</h1>
      )}
      <p>Enter your name:</p>
      <input
        name="username"
        type="text"
        onChange={handleChange}
      />
    </form>
  )
}

ReactDOM.render(<MyForm />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>


<div id="root"></div>

为了简单起见,您可以使用钩子、函式式组件、行内 jsx 运算子和解构。

uj5u.com热心网友回复:

资料型别username不是布林值而是字符串,字符串验证使用!== ''

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *