【发布时间】:2021-12-11 04:32:18
【问题描述】:
我正在以更新位置的形式更新详细信息。 我需要在表单字段中显示现有值。
下面是更新组件的代码:
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.
}
【问题讨论】:
-
抱歉“注册”道具的结构如何?为什么有“数据-”属性? (注意通常html元素上的属性被转换为他们的javascript api实现而不是kebab-case html属性)
-
props 的结构是最后一个 json 代码 sn-p 。 data-* 用于测试目的。你可以忽略它们
-
注册('公司',{必需:真})?这是一个函数而不是普通对象,对吧?
-
我需要在下拉列表中显示选定的值,但 id 嵌套在 props 对象中
-
注册('公司',{必需:真})?用于反应表单钩子
标签: reactjs react-hooks next.js react-hook-form