英文:
How to destructure component props if they aren't always present
问题
我有一个表单组件,它从其父组件获取'values'和'errors'作为props。
我正在使用remix run,所以我不需要将props保留为状态。我也不总是需要将errors作为props之一传递下去。
const Form = ({ values, errors }) => {
...
}
是否有一种方法可以使用扩展操作符只解构传递下来的props,或者我应该无论如何都传递一个空值给errors?
谢谢!
英文:
I have a Form component that gets both 'values' and 'errors' as props from its parent.
I am using remix run, so I don't need to keep the props as state. I also don't always need to pass down errors as one of the props.
const Form = ({values,errors}) => {
...
}
Is there a way to use the spread operator to only destructure props being passed down, or should i simply be passing an empty value for errors anyway?
Thanks!
答案1
得分: 2
你可以指定一个默认值:
const Form = ({values, errors} = {}) => {
...
}
英文:
You can assign a default value:
const Form = ({values,errors} = {}) => {
...
}
答案2
得分: 1
感谢您的回复(它们帮助我找到答案),我曾经认为,如果我尝试解构 props 并且它们没有被父组件设置,那么会引发错误,但似乎并非如此。
父组件:
<Form cat="Tom" />
表单组件:
const Form = ({ cat, dog, hamster, rabbit }) => {
if (dog !== undefined) {
// 做一些操作
}
}
英文:
Thanks for the responses (they helped me get to the answer), I had thought that if I tried to destructure the props and they hadn't been set by the parent it would cause errors, but that doesn't seem to be the case.
Parent:
<Form cat="Tom" />
Form component:
const Form = ({cat,dog,hamster,rabbit}) => {
if (dog !== undefined) {
// do something
}
}
答案3
得分: 0
以下是翻译好的部分:
常见的模式是将错误默认设置为空数组(因为可能不止一个),以防没有错误。
但也有一些库在没有问题时将其实现为未定义,这真的取决于情况。
在表单验证的情况下,请参考:
https://formik.org/docs/api/formik#errors--field-string-string-
以了解一些库如何处理这个问题。
英文:
A common pattern is to have errors as an empty array by default ( since there maybe be more than one ) in case there are no errors.
But there are also libraries that implement it as undefined when nothing went wrong, it really depends on the situation.
In the case of form validations see:
https://formik.org/docs/api/formik#errors--field-string-string-
to understand how some libraries approach that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论