首页 > 解决方案 > 成功提交表单时重定向错误 - 不工作

问题描述

我正在尝试在我的表单提交方法中添加几行,以处理表单组件在提交时使用初始状态值重新渲染。自从我添加了这些行以来,我一直无法让它正确提交,并且我还想在后端成功保存时实现某种成功消息。

在 axios.post 行之后我的语法是否正确?如果提交成功,它意味着重定向。

如果我添加成功的错误提交消息,我需要在后端还是在这个方法中处理它们?

const DiveLogForm = (props) => {

....

        // state for the current field value
        const [dive, setDive] = useState({
            diveTypeID: ``,
            diveSchoolID: ``,
            currentID: ``,
            visibilityID: ``,
            diveDate: ``,
            diveMaxDepth: ``,
            userID: props.user.userID,
            diveVerifiedBySchool: false,
            diveNotes: ``,
            diveSpotID: ``,
            redirectToForm: false,
            error: '',
            id: ''
        });

        .....

        const jwt = auth.isAuthenticated()

        ...

        function handleSubmitDive(e: React.FormEvent<HTMLFormElement>) {
            e.preventDefault();
            const formData = new FormData();
            formData.append("diveTypeID", dive.diveTypeID);
            formData.append("diveSchoolID", dive.diveSchoolID);
            formData.append("currentID", dive.currentID);
            formData.append("visibilityID", dive.visibilityID);
            formData.append("diveDate", dive.diveDate);
            formData.append("diveMaxDepth", dive.diveMaxDepth);
            formData.append("userID", dive.userID);
            formData.append("diveVerifiedBySchool", dive.diveVerifiedBySchool);
            formData.append("diveNotes", dive.diveNotes);
            formData.append("diveSpotID", dive.diveSpotID);
            formData.append("photos", photos);
            const config = {
                headers: {
                    'content-type': 'multipart/form-data'
                }
            };
            axios.post("http://localhost:5002/api/divelog/createdivelog", jwt.token, formData, config)
            .then((data) => {
            if (data && data.error) {
                setDive({...dive, error: data.error})
            } else {
                setDive({...dive, 'redirectToForm': true})
            }
        })
        }

标签: reactjsaxiosform-data

解决方案


推荐阅读