我正在努力以更新位置的形式更新详细信息。 我需要在表单字段中显示现有值。
下面是更新组件的代码:
import axios from 'axios'
import { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'
export default function Edit({...props}) {
const {
register,
handleSubmit,
setValue,
reset,
formState: { errors },
} = useForm({mode: 'onBlur' });
useEffect(() => {
if (props.locationDetails) {
console.log(props.locationDetails)
// in this console I can get { 'name' : 'name value', 'company' : 'UUID'}
reset( props.locationDetails);
}
}, [reset])
const editLocation = async(data) => {
.....
}
return (
<form className="g-3" onSubmit={handleSubmit(editLocation)} data-testid="editLocationForm">
<input type="text" {...register('name', { required: true })} className="form-control" placeholder="Enter Name Here" />
{errors.name && <p className="error" role="error" >Name is required.</p>}
<select {...register('company', { required: true })}
className="form-control" >
{props.companies && props.companies.map((company, index) => {
<option key={index} value={company.UUID}>{company.name}</option>
}
)}
</select>
.....
</form>
)
}
export async function getServerSideProps({ params }) {
if(params.id) {
let locationId = params.id
let locationResponse = await axios(process.env.BASE_URL + '/locations/' + locationId,{
headers : {
'Content-Type': 'application/json',
'Authorization' : 'Bearer ' + process.env.TOKEN
}
})
let companiesResponse = await axios(process.env.BASE_URL + '/companies',{
headers : {
'Content-Type': 'application/json',
'Authorization' : 'Bearer ' + process.env.TOKEN
}
})
if(locationResponse.status == 200 && locationResponse.data && companiesResponse.status == 200) {
let locationDetails = await locationResponse.data
let companies = await companiesResponse.data.results
locationDetails.company = locationDetails.links.Company
return {
props : {
locationDetails: locationDetails,
companies: companies
}
}
} else {
return {
props : {
locationDetails: {},
locationDetails:{}
}
}
}
} else {
return {
props : {
locationDetails: {},
locationDetails:{}
}
}
}
}
在这里,我可以在输入文本字段中设置位置的所有现有值,但无法显示选定的下拉列表。
响应结构如下:
{
"name": "New York",
"country": "USA",
"company": "UUID" <<<< this is the uuid which needs to be selected on select dropdown.
}
最佳答案
对于嵌套字段,在属性之间添加点:
<select {...register("links.company", { required: true })}>
{(companies || []).map((company, index) => (
<option key={index} value={company.UUID}>
{company.name}
</option>
))}
</select>
关于reactjs - React-hook-form 使用重置选择下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69712300/