如何在 yup 中为 react-select(单选)分配对象验证

Tar*_*uni 8 reactjs react-select yup formik

我正在尝试使用 yup 概念实现对 react-select(单选)的验证。但我收到此错误:

对象作为 React 子对象无效(找到:带有键 {label, value} 的对象)。如果您打算渲染一组子项,请改用数组。

我想知道如何在验证模式中为 yup 概念分配对象

<Formik
  initialValues={{
    department:"",
  }}
  onSubmit={this.submitForm}
  validationSchema={Yup.object().shape({
    department: Yup.object().shape({
      label: Yup.string().required(),
      value: Yup.string().required(),
    }),
})}>
{ props => {
  const {
    values,
    touched,
    errors,
    isSubmitting,
    handleChange,
    handleBlur,
    handleSubmit,
    selectedOption
  } = props;
  return (
    <React.Fragment>

    <InputLabel shrink htmlFor={'department'}>
    Department</InputLabel>
    <Select
          inputId="department"
          options={options}
          value={values.department}
          onChange={this.onChangeOption}
          onBlur={handleBlur}         
       />
{errors.department && touched.department && ( {errors.department} )} 
Submit </div> </React.Fragment> ); }} 
Run Code Online (Sandbox Code Playgroud)

J. *_*ers 11

我想知道如何在验证模式中为 yup 概念分配对象

你做对了(据我所知):

validationSchema={Yup.object().shape({
  department: Yup.object().shape({
    label: Yup.string().required(),
    value: Yup.string().required(),
  })
}
Run Code Online (Sandbox Code Playgroud)

React 抱怨的是这一行:

{errors.department && touched.department && ( {errors.department} )} 
Run Code Online (Sandbox Code Playgroud)

这评估的是如果errors有一个键被调用department,如果touched有一个键被调用,department则渲染对象errors.department。React 做不到这一点。如果您想显示错误,我建议<p>您在选择之外使用专用组件(例如标签)。像这样的东西:

{errors.department && touched.department && (<p>{errors.department.label}</p>)}
Run Code Online (Sandbox Code Playgroud)

您可以为value.

PS:您的代码似乎不完整且格式不佳(例如,有一个浮动<div />标签)。