[英]Best way too check the false & true condition in React Js
what is the best way to check the false & true condition in this case, i have a state set to false initially在这种情况下检查 false & true 条件的最佳方法是什么,我最初将 state 设置为 false
status: false,
The status changes to true if a certain props is present (data-widget) do i need to add the ="true" to the attribut?如果存在某个道具(数据小部件),状态会变为 true 我是否需要将 ="true" 添加到属性中?
<div id="app" data-widget></div>
// Is it the same thing or i don't need to add the ="true" to the attribut
<div id="app" data-widget="true"></div>
Here is how i check a condition, i am confused which one i should use:这是我检查条件的方法,我很困惑应该使用哪个条件:
//Option 1
newData.status = this.props.widget ? true : false
//Option 2
newData.status = (typeof this.props.widget !== "undefined") ? true : false
Is there a better/correct way to handle the false & true condition?有没有更好/正确的方法来处理 false & true 条件?
They are both same, but 'option2' is just checking if the value exist and is better for handling errors.它们都是相同的,但“option2”只是检查值是否存在并且更适合处理错误。 So I think it will be better to use the second option.
所以我认为使用第二个选项会更好。 And some attributes have default value, I think "data-widget" have default true
有些属性有默认值,我认为“data-widget”有默认值
Is there a better/correct way to handle the false & true condition?
有没有更好/正确的方法来处理 false & true 条件?
There's no " the best" way, it all depends on conditions.没有“最好”的方法,这完全取决于条件。 Even if they are looking similar they strongly differ.
即使它们看起来相似,它们也有很大的不同。 The first option will evaluate to
true
if props.widget
is truthy - (it's either an array , object , true, number (different that 0
) or a non-empty string.如果
props.widget
是真实的——(它是一个数组、 object 、真、数字(与0
不同)或非空字符串),第一个选项将评估为true
。
However the second one will evaluate to true
if props.widget
is not equal to undefined .然而,如果
props.widget
不等于undefined ,第二个将评估为true
。 It will evaluate to false
ONLY if props.widget
is undefined
.只有当
props.widget
是undefined
时,它才会评估为false
。
Anyways, if it's acceptable for your conditions, I would go with simple checking the truthyness of props.widget
:无论如何,如果您的条件可以接受,我会 go 简单地检查props.widget的
props.widget
:
newData.status = Boolean(this.props.widget); // will evaluate to true or false
// with no need to use ternary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.