Javascript 在React useState中使用(或| | |)语法进行赋值
我正在观察一种以前在react-useState钩子中没有见过的新语法。它是Javascript 在React useState中使用(或| | |)语法进行赋值,javascript,reactjs,syntax,react-hooks,logic,Javascript,Reactjs,Syntax,React Hooks,Logic,我正在观察一种以前在react-useState钩子中没有见过的新语法。它是 const[thing,setThing]=useState(thing | | otherThing)const[thing,setThing]=useState(thing | | otherThing) 如果thing或otherThing中的任何一个计算结果为真实表达式,则调用useState(true),并返回包含两个项的元组 如果thing和otherThing的计算结果都不是真实的表达式,则调用useS
const[thing,setThing]=useState(thing | | otherThing)代码>const[thing,setThing]=useState(thing | | otherThing)代码>
如果thing
或otherThing
中的任何一个计算结果为真实表达式,则调用useState(true)
,并返回包含两个项的元组
如果thing
和otherThing
的计算结果都不是真实的表达式,则调用useState(false)
,并返回一个包含两个项的元组
非真实表达的一些例子:
false
null
未定义
”
[]
{}
1+1==3
它只是用作声明回退的简洁语法。如果第一个变量是falsy,它将返回到第二个变量
第一个值为null
的示例:
const{useState}=React;
常数测试=空;
常量回退=‘回退’;
常量示例=()=>{
常量[状态,设置状态]=使用状态(测试| |回退);
log(“state:,state);//记录回退的值
返回
}
ReactDOM.render(,document.getElementById('root'))代码>
Javascript中的将返回第一个可以转换为true的值
这不是唯一的反应,它是一个烤在香草JS操作符,你可以在任何地方使用
以下是一些示例(取自MDN):
注意:如果使用此运算符为某个变量提供默认值,请注意,不会使用任何falsy值。如果只需要滤除空值或未定义,请考虑使用
如果thing
是truthy,它将用于初始化useState
。如果是falsy,则将使用其他东西。这是否回答了您的问题?
o1 = true || true // t || t returns true
o2 = false || true // f || t returns true
o3 = true || false // t || f returns true
o4 = false || (3 == 4) // f || f returns false
o5 = 'Cat' || 'Dog' // t || t returns "Cat"
o6 = false || 'Cat' // f || t returns "Cat"
o7 = 'Cat' || false // t || f returns "Cat"
o8 = '' || false // f || f returns false
o9 = false || '' // f || f returns ""
o10 = false || varObject // f || object returns varObject