有没有办法修复这个 PropType 错误,它说我将 fromData 作为字符串而不是对象传递

问题描述 投票:0回答:1

这是我从网页控制台收到的错误

警告:道具类型失败:提供给

formData
的类型为
string
的道具
FirstSection
无效,预期为
object
。 在 FirstSection (http://localhost:5173/src/Components/applySections/FirstSection.jsx?t=1708303938624:14:25) 在 ApplicationForm (http://localhost:5173/src/Containers/ApplicationForm.jsx?t 在路由(http://localhost:5173/node_modules/.vite/deps/react-router-dom)

我是网络开发的初学者,当我在 FirstSection.jsx 中使用 formData 时,出现上述错误。所以我正在制作一份分为不同部分的申请表。我已将这些不同的部分实现为不同的文件,例如第一节.jsx、第二节.jsx、第三节.jsx;除此之外,还有一个父组件 ApplicationForm.jsx,我在其中组合所有这些部分来完成我的申请表。我已经使用 formData 实现了这些部分,以便可以轻松地从父组件渲染它。

下面是我的ApplicationForm.jsx,它是父组件:

// eslint-disable-next-line no-unused-vars
import React, { useState } from 'react';

import FirstSection from '../Components/applySections/FirstSection';
import SecondSection from '../Components/applySections/SecondSection';
import ThirdSection from '../Components/applySections/ThirdSection';
import FourthSection from '../Components/applySections/FourthSection';
import FifthSection from '../Components/applySections/FifthSection';
import SixthSection from '../Components/applySections/SixthSection';
import SeventhSection from '../Components/applySections/SeventhSection';
import './ApplicationForm.css';

const ApplicationForm = () => {
    const [formData, setFormData] = useState({
        FirstSection: {},
        SecondSection: {},
        ThirdSection: {},
        FourthSection: {},
        FifthSection: {},
        SixthSection: {},
        SeventhSection: {},
    });

    const [showReview, setShowReview] = useState(false);

    const handleFormChange = (section, data) => {
        setFormData((prevData) => ({
          ...prevData,
          [section]: data,
        }));
    };

    const handleReview = () => {
        setShowReview(true);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        try{
            await fetch('localhost:5000/applications', {
                method: 'POST', 
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(formData),
            })
            console.log('Submitting Form');
            alert("Your application has been submitted successfully!");
        } catch(err){
            console.log(err);
            alert("An error occurred while submitting your application. Please try again later.");
        }
    };

    return (
        <div className='application-form-container'>
            <FirstSection formData={formData.FirstSection} onFormChange={(data) => handleFormChange("FirstSection", data)} />
            <SecondSection formData={formData.SecondSection} onFormChange={(data) => handleFormChange("SecondSection", data)} />
            <ThirdSection formData={formData.ThirdSection} onFormChange={(data) => handleFormChange("ThirdSection", data)} />
            <FourthSection formData={formData.FourthSection} onFormChange={(data) => handleFormChange("FourthSection", data)} />
            <FifthSection formData={formData.FifthSection} onFormChange={(data) => handleFormChange("FifthSection", data)} />
            <SixthSection formData={formData.SixthSection} onFormChange={(data) => handleFormChange("SixthSection", data)} />
            <SeventhSection formData={formData.SeventhSection} onFormChange={(data) => handleFormChange("SeventhSection", data)} />

            <button onClick={handleReview}>Review</button>
            <button onClick={handleSubmit}>Submit</button>

            {showReview && (
                <div className="review-modal">
                    <h2>Review Your Information</h2>
                    {/* Display a summary of entered information */}
                    {/* You can format and display the information as needed */}
                    <pre>{JSON.stringify(formData, null, 2)}</pre>
                    <button onClick={() => setShowReview(false)}>Close</button>
                </div>
            )}
        </div>
    );

    
};

export default ApplicationForm;

这是我的 FirstSection.jsx:

import React from 'react';
import PropTypes from 'prop-types';
import './FirstSection.css'

const FirstSection = ({ formData = {}, onFormChange }) => {
  const updateFormData = (field, value) => {
    onFormChange(field, value);
  };

所以问题是上述错误意味着什么以及如何修复它?

我尝试编写内联代码,以确保从父组件渲染的 formData 确实是一个对象,但错误仍然存在。

reactjs frontend form-data react-proptypes
1个回答
0
投票

更新

FirstSection
组件以处理
formData
不是对象的情况。一种方法是在使用
formData
之前检查它是否是一个对象。如果不是对象,可以将其设置为空对象。这是您的
FirstSection
组件的更新版本:

import React from 'react';
import PropTypes from 'prop-types';
import './FirstSection.css';

const FirstSection = ({ formData, onFormChange }) => {
  const updateFormData = (field, value) => {
    onFormChange(field, value);
  };

  // Check if formData is an object, otherwise set it to an empty object
  if (typeof formData !== 'object' || formData === null) {
    formData = {};
  }

  // Rest of your component code
};

FirstSection.propTypes = {
  formData: PropTypes.object,
  onFormChange: PropTypes.func.isRequired,
};

export default FirstSection;

说明: 添加对

typeof formData !== 'object' || formData === null
的检查并将
formData
设置为空对象(如果它不是对象),您应该能够解决该警告。

这确保了

formData
始终被视为一个对象,即使它没有从父组件正确提供。


PS:如果这回答了您的问题,请记住将其标记为已回答和/或如果您喜欢它,请点赞! :-) https://stackoverflow.com/help/someone-answers

© www.soinside.com 2019 - 2024. All rights reserved.