【问题标题】:How to update select items based on the selection from the first select items using react如何使用反应根据从第一个选择项目中的选择更新选择项目
【发布时间】:2020-10-30 18:24:17
【问题描述】:

我有一个这样的对象数组:

 const items = [ 
  { country:"USA", level:1},
  { country:"Canada", level:2},
  { country:"Bangladesh", level:3},
]

在我的表单组件中(我正在使用 React Formik 库)我正在渲染这样的项目:

     <Field name="color" as="select" placeholder="Favorite Color">
         {items.map((item,index)=>(
           <option>{item.country}</option>
         ))}
    </Field>
    <Field name="color" as="select" placeholder="Favorite Color">
         {items.map((item,index)=>(
           <option>{item.level}</option>
         ))}
    </Field>

现在,我需要根据第一个选择输入中的项目选择来更新第二个选择项的值。例如,当我从第一个选择中选择“USA”时,在第二个选择中它将更新值并呈现“1”。任何想法或建议将不胜感激。 到目前为止,我的组件如下所示:

import React from 'react';
import { Formik, Field } from 'formik';
import { Modal } from 'react-bootstrap';

const AddNewForm = () => {
const items = [ 
  { country:"USA", level:1},
  { country:"Canada", level:2},
  { country:"Bangladesh", level:3},
]
const handleUpdate = () => {
  console.log("change value...")
}
return (
    <div>
  <Formik
  initialValues={{ country: '', level: '' }}
  onSubmit={(values, { setSubmitting }) => {
    setTimeout(() => {
      alert(JSON.stringify(values, null, 2));
      setSubmitting(false);
    }, 400);
  }}
>
  {({
    values,
    errors,
    touched,
    handleChange,
    handleBlur,
    handleSubmit,
    isSubmitting,
    /* and other goodies */
  }) => (
    <form onSubmit={handleSubmit}>
      <Field name="country" as="select" onChange={handleUpdate}>
         {items.map((item,index)=>(
           <option>{item.country}</option>
         ))}
    </Field>
    <Field name="level" as="select">
         {items.map((item,index)=>(
           <option>{item.level}</option>
         ))}
    </Field>
    <Modal.Footer>
    <button type="submit" disabled={isSubmitting}>
        Save
      </button>
      </Modal.Footer>
    </form>
  )}
</Formik>
    </div>
)

}导出默认的AddNewForm;

【问题讨论】:

  • 你使用的是类还是函数组件?
  • 到目前为止您尝试过什么?是否创建了 Field 组件的 onChange/onSelect 方法?
  • 我正在使用功能组件并添加了我迄今为止一直在使用的组件,是的,我知道我应该传递一个 onChange 处理程序方法,但不确定实现该操作的逻辑是什么
  • 您能否在代码沙箱或其他任何地方创建此问题的副本?这样我就可以查看错误(如果有)。
  • @ManishSundriyal,这是我们一直在尝试修复的沙盒链接stackblitz.com/edit/react-wp4tmq。 “级别”字段仍然存在一个问题。即使根据国家/地区的选择过滤了 level 的值,在 OnSubmit 上传递的值仍然为空,除非我们更改“level”字段中的值。如果你能帮助我们就好了

标签: reactjs formik


【解决方案1】:

正如我之前写的...不需要手动管理状态,Formik 会为我们管理它

当使用&lt;Field/&gt; 时,需要带有功能组件/钩子的版本 - useFormikContext(以及 &lt;Formi /&gt; 作为父/上下文提供者)。您可以将useFormik(并且没有父级)与普通的 html 输入一起使用。

外部组件:

export default function App() {
  const items = [
    { country: "USA", level: 1 },
    { country: "USA", level: 5 },
    { country: "Canada", level: 2 },
    { country: "Canada", level: 4 },
    { country: "Bangladesh", level: 2 },
    { country: "Bangladesh", level: 7 }
  ];

  return (
    <div className="App">
      <h1>connected selects</h1>
      <Formik
        initialValues={{ country: "", level: "" }}
        onSubmit={values => {
          console.log("SUBMIT: ", values);
        }}
      >
        <Form data={items} />
      </Formik>
    </div>
  );
}

外部组件(父&lt;Formik /&gt;)职责:

  • 初始化
  • 主要处理程序(提交)
  • 验证

内部组件职责:

  • 数据作为道具传递;
  • 本地数据过滤(通过钩子避免不必要的重新计算);
  • 字段依赖的本地处理程序;
  • 视觉条件变化

内部组件:

import React, { useState, useEffect } from "react";
import { Field, useFormikContext } from "formik";
import { Modal } from "react-bootstrap";

const AddNewForm = props => {
  const items = props.data;

  // derived data, calculated once, no updates
  // assuming constant props - for changing useEffect, like in levelOptions
  const [countryOptions] = useState(
    Array.from(new Set(items.map(item => item.country)))
  );
  const [levelOptions, setLevelOptions] = useState([]);

  const {
    values,
    handleChange,
    setFieldValue,
    handleSubmit,
    isSubmitting,
    isValid // will work with validation schema or validate fn defined
  } = useFormikContext();

  const myHandleChange = e => {
    const selectedCountry = e.target.value;

    debugger;
    // explore _useFormikContext properties
    // or FormikContext in react dev tools

    console.log("myHandle selectedCountry", selectedCountry);
    handleChange(e); // update country

    // available levels for selected country
    const levels = items.filter(item => item.country === selectedCountry);
    if (levels.length > 0) {
      // update level to first value
      setFieldValue("level", levels[0].level);
      console.log("myHandle level", levels[0].level);
    }
  };

  // current values from Formik
  const { country, level } = values;

  //  calculated ususally on every render
  //
  // const countryOptions = Array.from(new Set(items.map(item => item.country)));
  // const levelOptions = items.filter(item => item.country === country);
  //
  //  converted into hooks (useState and useEffect)
  //
  useEffect(() => {
    // filtered array of objects, can be array of numbers
    setLevelOptions(items.filter(item => item.country === country));
  }, [items, country]); // recalculated on country [or items] change

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <Field
          name="country"
          value={country}
          as="select"
          onChange={myHandleChange} // customized handler
        >
          {!country && (
            <option key="empty" value="">
              Select Country - disappearing empty option
            </option>
          )}
          {countryOptions.map((country, index) => (
            <option key={country} value={country}>
              {country}
            </option>
          ))}
        </Field>
        {country && (
          <>
            <Field
              name="level"
              as="select"
              onChange={handleChange} // original handler
            >
              {levelOptions.map((item, index) => (
                <option key={item.level} value={item.level}>
                  {item.level}
                </option>
              ))}
            </Field>

            <Modal.Footer>
              <button type="submit" disabled={!isValid && isSubmitting}>
                Save
              </button>
            </Modal.Footer>
          </>
        )}
      </form>
      <>
        <h1>values</h1>
        {country && country}
        <br />
        {level && level}
      </>
    </div>
  );
};

export default AddNewForm;

工作 demo,可探索/可调试 iframe here

它是否满足所有功能要求?

【讨论】:

  • 看来这就是我想要的,我会尽快用我的实际功能尝试该解决方案,但现在首先为此 +1,非常感谢
【解决方案2】:

试试这个。

import React, {useState} from "react";
import { Formik, Field } from "formik";
import { Modal } from "react-bootstrap";

const AddNewForm = () => {

  const items = [
    { country: "USA", level: 1 },
    { country: "Canada", level: 2 },
    { country: "Bangladesh", level: 3 },
  ];

  return (
    <div>
      <Formik
        initialValues={{ country: "", level: "" }}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 400);
        }}
      >
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          isSubmitting
          /* and other goodies */
        }) => (
          <form onSubmit={handleSubmit}>
            <Field name="country" as="select" onChange={handleChange} >
              <option value='' defaultValue>Select Country</option>
              {items.map((item, index) => (
                <>
                <option value={item.country} >{item.country}</option>
                </>
              ))}
            </Field>
            <Field name="level" as="select" onChange={handleChange} >
            <option value='' defaultValue>Select Level</option>
              {items.filter((item)=>item.country===values.country).map((item, index) => (
                <option>{item.level}</option>
              ))}
            </Field>
            <Modal.Footer>
              <button type="submit" disabled={isSubmitting}>
                Save
              </button>
            </Modal.Footer>
          </form>
        )}
      </Formik>
    </div>
  );
};

export default AddNewForm;

试试这个工作demo

【讨论】:

  • 状态重复,Formik在values内部管理值
  • 感谢您的解决方案,对组件的推进很有帮助,虽然最初在第二个下拉选择中没有出现,但我期待第一个下拉列表中的默认选择是“美国" 那么它也会在第二个下拉菜单中最初呈现相应的级别“1”
  • const [selectedCountry,setSelectedCountry] = useState('') 如果你在useState 中提供默认值,它会。例如,尝试useState('Canada')。最初没有选择任何内容。
  • 一切正常,但现在的问题是当我提交到“保存”按钮时它没有发送任何值
  • @saon 你可以有多个国家和多个级别,对吧?
最近更新 更多