【发布时间】:2022-11-23 04:12:01
【问题描述】:
我正在使用 React 和 API 来获取数据并将其预填充到表单字段中,以便用户可以编辑现有记录。
但是,子组件似乎只接收一开始创建的 longhorn 实体的版本,而不是 API 获取的版本,也无法更新。
相关父页面代码:
React.useEffect(() => {
async function getLonghorn() {
let response = await fetch(`http://127.0.0.1:8081/longhorns/${longhornID}`, { method: 'get' })
let data = await response.json();
setLonghorn(await data[0]);
};
if (longhorn.Name === "") {
getLonghorn();
}
}, [longhorn.Name, longhornID]);
return (
<>
<Navbar />
<AdminImageUploadUI type="longhorn" id={longhornID} imageList={imageList}></AdminImageUploadUI>
<AdminEditLonghornForm {...longhorn} ></AdminEditLonghornForm>
</>
)
相关子组件代码:
import React from 'react'
import { render } from 'react-dom';
import GetRequest from '../../Get';
type props = {
LonghornID: number,
Name: string,
RanchPrefix: string,
RoleID: number,
SexID: number,
IsExternal:number,
FatherLonghornID:number,
MotherLonghornID: number,
ReferenceNumber: string,
DOB: string,
Description:string};
class AdminEditLonghornForm extends React.Component<{}, {
LonghornID: number,
Name: string,
RanchPrefix: string,
RoleID: number,
SexID: number,
IsExternal:number,
FatherLonghornID:number,
MotherLonghornID: number,
ReferenceNumber: string,
DOB: string,
Description:string,
message: string}>
{
constructor(props: props) {
super(props)
this.state = {
LonghornID: props.LonghornID,
Name: props.Name,
RanchPrefix: props.RanchPrefix,
RoleID: props.RoleID,
SexID: props.SexID,
IsExternal: props.IsExternal,
FatherLonghornID: props.FatherLonghornID,
MotherLonghornID: props.MotherLonghornID,
ReferenceNumber: props.ReferenceNumber,
DOB: props.DOB,
Description: props.Description,
message: ''
}
}
如果我 console.log 父对象中的 longhorn 对象,它会多次复制日志,在前三个左右显示空的默认数据集,然后在最后几个日志中显示填充的数据。在孩子中记录收到的道具每次都会显示空数据。我已经尝试创建一个新对象并在发送的道具列表中对其进行解构,但它成为显示问题的相同初始数据的受害者。
我怀疑这是对 React.UseEffect 的误用,但我不得不依赖它来使我的异步获取功能正常工作。对不起,如果我的代码和结构有点乱,对 JavaScript 来说还是新手
【问题讨论】:
-
await data[0]?你为什么在那里有一个await?
标签: reactjs typescript react-hooks fetch-api