如何解决错误:对象作为 React 子对象无效找到:键为 {value} 的对象如果您打算渲染一组子项,请改用数组
我已经阅读了许多关于同一错误的问题,但无法理解在我的情况下发生了什么。在其他问题上,此错误是 caused by an object being used as a React child 或由传递的多个 prop 属性引起。
我正在尝试设置 formik
和 yup
以根据月份字段验证日字段,两者都使用 react-select
,这样如果月份是二月,那么允许的最大天数是 29。就是这样...
我设法在 CodesandBox 中重现了错误:https://codesandbox.io/s/formik-yup-reactselect-rmd9f?file=/src/App.js
如果您选择第 29 天和任何月份,则它有效,但如果您选择第 30 天和二月,则会出现此错误,我无法找出问题所在:
未捕获的错误:对象作为 React 子对象无效(找到:键为 {value} 的对象)。如果您打算渲染一组子项,请改用数组。
代码是:
import { Button } from "@chakra-ui/button";
import {
FormControl,FormErrorMessage,Formlabel,} from "@chakra-ui/form-control";
import { Center,Stack } from "@chakra-ui/layout";
import { Formik,Form,useField,useFormikContext } from "formik";
import * as Yup from "yup";
import Select from "react-select";
const SelectInput = ({ label,options,...props }) => {
const [field,Meta,helper] = useField(props);
const { values,setFieldValue } = useFormikContext();
return (
<FormControl id={props.id} isInvalid={Meta.touched && Meta.error}>
<Formlabel>{label}</Formlabel>
<Select
{...field}
{...props}
options={options}
onBlur={helper.setTouched}
value={values[field.name]}
onChange={(value) => setFieldValue(field.name,value)}
/>
<FormErrorMessage>{Meta.error}</FormErrorMessage>
</FormControl>
);
};
const SignupForm = () => {
const days = [
{ value: 29,label: "29" },{ value: 30,label: "30" },];
const months = [
{ value: 0,label: "January" },{ value: 1,label: "February" },];
return (
<Formik
initialValues={{
day: "",month: "",}}
validationSchema={Yup.object({
day: Yup.object()
.shape({
value: Yup.number().required(),label: Yup.string().required(),})
.when("month",{
is: (month) => {
return month?.value === 1;
},then: Yup.object().shape({
value: Yup.number()
.required()
.max(29,`This month has only 29 days`),}),month: Yup.object().shape({
value: Yup.number().required(),})}
onSubmit={(values,{ setSubmitting }) => {
alert(JSON.stringify(values,null,2));
setSubmitting(false);
}}
>
<Form>
<Center>
<Stack
spacing={4}
padding={4}
width="50%"
>
<SelectInput
label="Day"
name="day"
type="text"
options={days}
instanceId="unique"
/>
<SelectInput
label="Month"
name="month"
type="text"
options={months}
instanceId="unique"
/>
<Button type="submit"> Register </Button>
</Stack>
</Center>
</Form>
</Formik>
);
};
export default SignupForm;
任何帮助将不胜感激:P
解决方法
meta.error
不保证是字符串。
如果你改变
<FormErrorMessage>{meta.error}</FormErrorMessage>
到
<FormErrorMessage>{JSON.stringify(meta.error)}</FormErrorMessage>
效果还不错。
虽然也没有显示错误...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。