什么?运算符均值 JavaScript
What does ?. operator mean in JavaScript
我正在使用 react-hook-form 并且遇到了 ?。操作员。这是什么意思?
这是有关如何使用它的一些上下文
<span>{errors?.name?.message}</span>
像这样从 useForm() 中解构错误的地方
const { register, handleSubmit, formState: { errors } } = useForm();
这里是一个完整的表格输入,以描绘更清晰的画面
<input
type="text"
id='name'
name='name'
{...register('name', {
required: {
value: true,
message: 'Name cannot be empty'
}
})}
placeholder='John Doe'
className='px-6 w-full rounded-md py-2 text-gray-700 focus:outline-none'
/>
<span>{errors?.name?.message}</span>
?.
是可选的链接运算符。这是 MDN 参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
例如,如果您运行下面的代码,您将面临一个错误
a = {}
console.log(a.b.c)
Uncaught TypeError: Cannot read property 'c' of undefined
但是如果你不想添加 try-catch,但是这个值不存在是可以接受的,那么你可以执行以下操作
a = {}
console.log(a.b?.c)
这将导致 undefined
被打印到控制台。访问c的错误被静默处理。
我正在使用 react-hook-form 并且遇到了 ?。操作员。这是什么意思? 这是有关如何使用它的一些上下文
<span>{errors?.name?.message}</span>
像这样从 useForm() 中解构错误的地方
const { register, handleSubmit, formState: { errors } } = useForm();
这里是一个完整的表格输入,以描绘更清晰的画面
<input
type="text"
id='name'
name='name'
{...register('name', {
required: {
value: true,
message: 'Name cannot be empty'
}
})}
placeholder='John Doe'
className='px-6 w-full rounded-md py-2 text-gray-700 focus:outline-none'
/>
<span>{errors?.name?.message}</span>
?.
是可选的链接运算符。这是 MDN 参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
例如,如果您运行下面的代码,您将面临一个错误
a = {}
console.log(a.b.c)
Uncaught TypeError: Cannot read property 'c' of undefined
但是如果你不想添加 try-catch,但是这个值不存在是可以接受的,那么你可以执行以下操作
a = {}
console.log(a.b?.c)
这将导致 undefined
被打印到控制台。访问c的错误被静默处理。