Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 选择国家/地区-空选项 )} {countryOptions.map((国家,索引)=>( {国家} ))} {国家&&( {levelOptions.map((项,索引)=>( {item.level} ))} 拯救 )} 价值观 {国家和国家&&country} {level&&level} ); }; 导出默认AddNewForm;_Reactjs_Formik - Fatal编程技术网

Reactjs 选择国家/地区-空选项 )} {countryOptions.map((国家,索引)=>( {国家} ))} {国家&&( {levelOptions.map((项,索引)=>( {item.level} ))} 拯救 )} 价值观 {国家和国家&&country} {level&&level} ); }; 导出默认AddNewForm;

Reactjs 选择国家/地区-空选项 )} {countryOptions.map((国家,索引)=>( {国家} ))} {国家&&( {levelOptions.map((项,索引)=>( {item.level} ))} 拯救 )} 价值观 {国家和国家&&country} {level&&level} ); }; 导出默认AddNewForm;,reactjs,formik,Reactjs,Formik,可工作、可探索/可消除缺陷的iframe 它是否满足所有功能要求?您使用的是类组件还是功能组件?到目前为止您尝试了什么?您是否已经创建了字段组件的onChange/onSelect方法?我正在使用functional component,并添加了到目前为止我一直在使用的组件,是的,我知道我应该传递一个onChange处理程序方法,但不确定那里的逻辑将实现什么,您可以在代码沙盒或其他任何地方创建此问题的副本吗?这样我就可以查看错误了。@ManishSundriyal,这是我们一直试图修复的沙盒链接

可工作、可探索/可消除缺陷的iframe


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

您使用的是类组件还是功能组件?到目前为止您尝试了什么?您是否已经创建了字段组件的onChange/onSelect方法?我正在使用functional component,并添加了到目前为止我一直在使用的组件,是的,我知道我应该传递一个onChange处理程序方法,但不确定那里的逻辑将实现什么,您可以在代码沙盒或其他任何地方创建此问题的副本吗?这样我就可以查看错误了。@ManishSundriyal,这是我们一直试图修复的沙盒链接。“级别”字段仍然存在一个问题。即使级别的值是根据国家/地区的选择进行过滤的,但在提交时传递的值仍然为空,除非我们更改“级别”字段中的值。如果您能帮助我们进行状态复制,那就太好了。Formik在
值中内部管理值
感谢您的解决方案,继续使用组件是很有帮助的,尽管最初在第二个下拉列表中的选择没有显示任何内容,但我希望第一个下拉列表中的默认选择是“USA”然后,它还将在第二个下拉列表中最初呈现相应的级别“1”,以及
const[selectedCountry,setSelectedCountry]=useState(“”)
如果您在
useState
中提供默认值,它将显示。例如,尝试
useState('Canada')
。最初没有选择任何内容。一切正常,但现在的问题是,当我提交到“保存”按钮时,它不会发送任何内容value@saon您可以有多个国家和多个级别,对吗?似乎这就是我想要的,我将很快尝试使用我真正的功能的解决方案,但现在,我首先要感谢+1
 const items = [ 
  { country:"USA", level:1},
  { country:"Canada", level:2},
  { country:"Bangladesh", level:3},
]
     <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>
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>
)
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;

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>
  );
}
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;