Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React useState中使用(或| | |)语法进行赋值_Javascript_Reactjs_Syntax_React Hooks_Logic - Fatal编程技术网

Javascript 在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

我正在观察一种以前在react-useState钩子中没有见过的新语法。它是


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