首页 > 解决方案 > 正确清理请求的数据 - 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
    )
}

问题

问题

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

标签: javascriptreactjstypescriptapisanitization

解决方案


推荐阅读