简体   繁体   English

如何在 React JS 编辑表单中的 select 下拉列表中显示所选选项

[英]How to display selected option in select dropdown in React JS edit form

I am using react-hook-form npm module for my edit data form.我正在为我的编辑数据表单使用react-hook-form npm 模块。 Here below is my API response sample:下面是我的 API 响应示例:

{
  UUID: "xxxxxx-bd10-473e-a765-xxxxxx"
  address1: "addr1"
  address2: "addr2"
  address3: ""
  city: "xxxxx"
  contact: "uxxxxxb"
  country: "xxxxxx"
  email: "xxxxxx@email.com"
  links: {Company: 'xxxxxx-4689-4689-8812-xxxxxxxxx'}
  name: "xxxxx"
  phone: "xxxxxxxx"
  state: "xxxxxxxx"
  zip: "11111"
}

Here below is the required code lines from the edit component下面是编辑组件中所需的代码行

    import axios from 'axios'  
    import { useForm } from 'react-hook-form'
    // Now getting the default list of all the companies
    Edit.getInitialProps = async (context) => {
      try {
        const companyResponse = await axios(process.env.BASE_URL + '/v1/companies',{
            headers : {
                'Content-Type': 'application/json',
                'Authorization' : 'Bearer ' + process.env.TOKEN
            }
        })
        if(companyResponse.status == 200) {
            return {
                companies : companyResponse.data.results
            }
        } else {
            return {companies: []}
        }
    } catch (error) {
        return {companies: []}
    }
  }
  
  export default function Edit({...props}) {

      const [selectedCompany, setSelectedCompany] = useState(0)

      const {
        register,
        handleSubmit,
        reset,
        formState: { errors },
      } = useForm({mode: 'onBlur' });
      

      useEffect(() => {
          // Here I am getting location existing value from API response i.e. the above json response
          setSelectedCompany(locationDetails.links.Company)  // setting state of existing company of location
      })

      return (

               <>
                <form className="g-3" onSubmit={handleSubmit(editLocation)} data-testid="editLocationForm">
                   <select {...register('company', { required: true })} className="form-control">
                   {(props.companies || []).map((company, index) => (
                    <option key={index} value={company.UUID} defaultValue={company.UUID === selectedCompany}>{company.name}</option>
                 ))}
               </select>


                .....
                </form>
            </>

  }

I need to display the existing value of company name as selected in the drop down.我需要显示在下拉列表中选择的公司名称的现有值。

From the react-hook-form documentation you have to use the setValue or reset methods of the hook, the setValue will only set the value of the field you specify, and the reset will reset the whole form and set initial values that you specifyreact-hook-form文档中,您必须使用钩子的setValuereset方法, setValue只会设置您指定的字段的值,而reset将重置整个表单并设置您指定的初始值

https://react-hook-form.com/api/useform/setvalue https://react-hook-form.com/api/useform/setvalue

https://react-hook-form.com/api/useform/reset https://react-hook-form.com/api/useform/reset

SetValue Approach设置值方法

useEffect(() => {
          // Here I am getting location existing value from API response i.e. the above json response
          setSelectedCompany(locationDetails.links.Company)  // setting state of existing company of location
          setValue('company', locationDetails.links.Company);
      })

Reset approach重置方法

useEffect(() => {
          // Here I am getting location existing value from API response i.e. the above json response
          setSelectedCompany(locationDetails.links.Company)  // setting state of existing company of location
          reset('company', locationDetails.links.Company);
      })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 React Js 在下拉列表中获取所选选项的值? - How to get value of selected option in a dropdown using React Js? 用户单击以及如何根据所选编辑选择下拉选项后,不会更改所选的reactjs单选按钮 - reactjs radio button selected is not changed after user click and how to select dropdown option based on the selected edit React-Select:如何显示空的redux表单 <Field /> 当用户从下拉菜单中选择“其他”选项时? - React-Select: How to display empty redux-form <Field /> when user selects “other” option from dropdown? 如何根据 React Js 中第一个下拉列表中的选定选项动态呈现不同的下拉列表 - How to render different dropdown list dynamically based on selected option in first dropdown in React Js 从 React.js 中的另一个下拉列表中选择一个选项时如何重置下拉列表值 - How to reset dropdown values when an option is selected from another dropdown in React.js 在反应js中保留antd select中的选定选项 - persist selected option in antd select in react js 如何有条件地禁用 React JS 中表单选择中的选项? - How do I conditionally disable an option in a form select in React JS? 使用多下拉菜单时获取反应选择选项 - Get react-select selected option when using multi dropdown Apollo React:如何从选择下拉列表中选择其他选项时重新获取查询? - Apollo React: How to refetch query when a different option is selected from select dropdown? React js中select表格中的过滤选项 - Filter option in form select in React js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM