无法完成对API的请求(React typescript - axios)

hmae6n7t  于 2023-04-30  发布在  iOS
关注(0)|答案(1)|浏览(117)

我用NSwag studio生成了typescript客户端。生成的代码有一部分:

user(authorization?: any | undefined, body?: AddUserDto | undefined , cancelToken?: CancelToken | undefined): Promise<NewUserDto> {
        let url_ = this.baseUrl + "/add_user";
        url_ = url_.replace(/[?&]$/, "");

        const content_ = JSON.stringify(body);

        let options_ = <AxiosRequestConfig>{
            data: content_,
            method: "POST",
            url: url_,
            headers: {
                "Authorization": authorization !== undefined && authorization !== null ? "" + authorization : "",
                "Content-Type": "application/json-patch+json",
                "Accept": "text/plain"
            },
            cancelToken
        };

        return this.instance.request(options_).catch((_error: any) => {
            if (isAxiosError(_error) && _error.response) {
                return _error.response;
            } else {
                throw _error;
            }
        }).then((_response: AxiosResponse) => {
            return this.processUser(_response);
        });
    }

react并不总是执行这行return this.processUser(_response);。我认为它与重新渲染组件有关,我试图使用上下文。但没有用。
方法调用链:

public addNewUser(id: number, name: string, surname: string, date: Date): Promise<NewUserDto>{
        let dto = new AddUserDto({ id: id, name: name, surname: surname, date: date });
        return this._add.user(this.getToken(), dto)
            .then(response => this.updateUser().then(() => response))
            .catch(error => {
                let apiError  = error as ApiException;

                if (apiError === null || apiError.status !== Unauthorized){
                    console.error(error);
                    this._tokenService.reset();
                    return new NewUserDto();
                }

                return this.updateToken()
                    .then(() => this._add.user(this.getToken(), dto))
                    .catch(error => {
                        console.error(error);
                        this._tokenService.reset();
                        return new NewUserDto();
                    });
            });
    }
const handleCreateNewUser = async (identifier: number, client: ApiClientWrapper, form: HTMLFormElement, date: Date): Promise<string> => {
    let name:string = "";
    let surname: string = "";
    for (let i = 0; i < form.length; i++){
        if (form[i].localName !== "input"){
            continue;
        }

        let element = (form[i] as HTMLInputElement);
        if (element.id === NAME_ID){
            name = element.value;
        }

        if (element.id === SURNAME_ID){
            surname = element.value;
        }
    };

    try {
        const response = await client.addNewUser(identifier, name, surname, date);
        return `Login: ${response.login}; Password: ${response.password}`;
    } catch (exception) {
        console.error(exception);
        return "";
    }
};
const AddUser: FC = () => {
    const [date, setDate] = useState(new Date());
    const [submitting, setSubmitting] = useState(false);
    const client = new ApiClientWrapper(useAppDispatch());
    const identifier = useAppSelector(selectUserIdentifier);
    const setMessage = useContext(MessageContext);
    return(
        <Form 
            className='main-account-container'
            onSubmit={event => {
                setSubmitting(true);
                let form = event.target as HTMLFormElement;
                handleCreateNewUser(identifier, client, form, date)
                    .then(message => { 
                        setMessage(message);
                        setSubmitting(false);
                        })
                    .catch(error => console.error(error));
                    }
                }
            >
        </Form>);
}
const AccountPage: FC = () => {
    const initialValues: IChangePasswordForm = { password: "", newPassword: "", confirmPassword: "" };
    const initErrors: IChangePasswordForm = { password: "", newPassword: "", confirmPassword: "" };
    const [submitting, setSubmitting] = useState(false);
    const [passwordForm, setPasswordForm] = useState(initialValues);
    const [errors, setErrors] = useState(initErrors);
    const [message, setMessage] = useState("");
    useEffect(() => {
        if (message !== ""){
            navigator.clipboard.writeText(message);
        }
    }, [message]);

    const displayedName = useAppSelector(selectUserName);
    const admin = useAppSelector(selectUserIsAdmin);
    const client = new ApiClientWrapper(useAppDispatch());
    return(
        <WorkingArea>
            <div className='account-page-root'>
                <div className='account-header'>{admin ? "Менеджер" : "Продавец"} {displayedName}</div>
                {admin ? <MessageContext.Provider value={setMessage}><AddUser /></MessageContext.Provider> : <Container />}
                {admin ? <RemoveUser /> : <Container />}
            </div>
        </WorkingArea>
    );
}

我尝试使用useRef作为消息的响应结果,useCallback作为handleCreateNewUser(它以onSubmit的形式执行),将'then'更改为'async/await',但调试器并不总是访问行return this.processUser(_response);(react没有抛出任何错误)。

zbsbpyhn

zbsbpyhn1#

我解决了这个问题。客户端丢失请求承诺,因为表单执行默认方案。必须禁用此方案。

<Form 
        className='main-account-container'
        onSubmit={event => {
            event.preventDefault();   <--- this one
            setSubmitting(true);
            let form = event.target as HTMLFormElement;
            handleCreateNewUser(identifier, client, form, date)
                .then(message => { 
                    setMessage(message);
                    form.reset();
                    setSubmitting(false);
                    })
                .catch(error => {
                    console.error(error);
                    form.reset();
                    setSubmitting(false);
                });
                }
            }
        >

相关问题