javascript - 正确清理请求的数据 - Typescript、React
问题描述
背景
我不确定我应该如何处理从 Java 后端获得的数据,以便在 React 表单中使用。反之亦然:在发出后端请求时清理我从表单中获得的数据。对于前端/后端通信,我们使用 OpenApi,它从 Java 中定义的 DTO 为我们生成 Typescript 接口和 API。
设想
Java中的模式示例:
public enum Pet {
CAT,
DOG
}
@Schema(description = "Read, create or update an account")
public class AccountDto {
@NotNull
private Boolean active;
@NotBlank
private String userName;
@NotNull
private Pet preferedPet;
@Nullable
private String bioDescription;
// Constructor and getter/setters skipped
}
当前实施
生成的 Typescript 接口示例:
enum Pet {
CAT,
DOG
}
interface AccountDto {
active: boolean,
userName: string,
preferedPet: Pet,
bioDescription?: string // Translates to: string | undefined
}
示例 React.js:
import {getAccount, updateAccount, Pet, AccountDto} from "./api"
export default function UpdateAccount() {
const [formData, setFormData] = useState<AccountDto>({
active: true,
userName: "",
preferedPet: Pet.CAT,
bioDescription: ""
})
useEffect(() => {
async function fetchAccount() {
const response = await getAccount();
// Omitted error handling
setFormData(response.data);
// response.data could look like this:
// {
// active: true,
// userName: "John",
// preferedPet: Pet.DOG,
// bioDescription: null
// }
}
}, [])
async function updateAccountHandler() {
const response = await updateAccount(formData);
// Omitted error handling
// Example formData object:
// {
// active: true,
// userName: "John",
// preferedPet: Pet.CAT,
// bioDescription: ""
// }
}
return (
// All input fields
)
}
问题
- 获取帐户时, bioDescription 是
null
. React 会抛出一个警告,指出组件(bioDescription 输入)正在从不受控制变为受控。 - 如果有任何机会为preferedPet 设置了null,我们将收到选择值无效的警告。
- 更新帐户时,所有空字符串都应为空。在我看来,数据库需要并且通常更清洁。
问题
1.) 我想知道其他 React 用户如何准备/清理他们的数据以供使用和请求。有没有我不知道的去或好的做法?
2.) 目前我正在使用以下功能来清理我的数据。它似乎有效,Typescript 没有通知我任何类型不匹配,但我认为它应该是因为 bioDescription 只能是string | undefined
而不是null
。
function sanitizeData<T>(data: T, type: "use" | "request"): T {
const sanitizedData = Object.create({});
for (const [key, value] of Object.entries(data)) {
if (!value && type === "use") {
sanitizedData[key] = "";
} else if (!value && type === "request") {
sanitizedData[key] = null;
} else {
sanitizedData[key] = value;
}
}
return sanitizedData;
}
我有一种情况,我试图在不使用 React setState 的情况下手动更改道具。
formData.description = null;
此时 Typescript 告诉我 null 是不可能的。这就是我检测到我的消毒剂功能可能不正确的方式。
演示
沙盒 - https://codesandbox.io/s/async-cdn-7nd2m?file=/src/App.tsx
解决方案
推荐阅读
- append - Power Query - 减去不连续的行并创建一个新行
- reactjs - 如何在 Nextjs 中导入两个组件
- docker - Gitlab CI。来自守护进程的错误响应:没有这样的图像
- protocol-buffers - 添加新消息后的 Proto2 编码/解码问题
- c - 为什么我在将 for 循环的乘积声明为 C 中的变量时收到此错误“错误:预期表达式”
- python - 当您知道嵌套键时访问嵌套字典?
- c++ - /d2vzeroupper MSVC 编译器优化标志在做什么?
- flutter - 我怎样才能制作这个 rtl - 颤动
- python - Numpy 获取具有当前值的邻居索引的最快方法(洪水填充)
- c# - 如何避免使用 EF Core 进行保存时的实体跟踪?