【问题标题】:Submitting a form in React typescript在 React 打字稿中提交表单
【发布时间】:2021-07-21 22:39:17
【问题描述】:

我正在尝试向本地数据库提交表单,但我不断收到错误消息:

:错误:对象作为 React 子项无效(发现:错误:网络错误)。如果您打算渲染一组子项,请改用数组

谁能告诉我发生了什么以及如何解决它?代码如下:

import axios from 'axios';
import type  { FC } from 'react';
import { useState } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import './AgentForm.css';

interface IFormInputs {
    firstName: string;
    lastName: string;
    photoUrl: string | null; 
    agentLicence: string; 
    address: string; 
    practiceAreas: string;
    aboutMe: string | null;
}

const AgentForm: FC = () => {
    const { register, handleSubmit, formState: {errors} } = useForm<IFormInputs>();
    const [error, setError] = useState<string>("");
    const [eventCreated, setEventCreated] = useState<boolean>(false);

    const submitForm: SubmitHandler<IFormInputs> = async (agent: IFormInputs) => {
        if (!agent.photoUrl) {
            agent.photoUrl = null;
        }
        if (!agent.aboutMe) {
            agent.aboutMe = null;
        }
        // console.log(JSON.stringify(agent))

        try {
            await axios.post('http://localhost:3001/agents', JSON.stringify({
                firstName: agent.firstName,
                lastName: agent.lastName,
                photoUrl: agent.photoUrl,
                agentLicence: agent.agentLicence, 
                address: agent.address, 
                practiceAreas: agent.practiceAreas,
                aboutMe: agent.aboutMe
            }));
            setEventCreated(true);
            setError('');
        } catch (error) {
            setError(error);
        }  
    }

  return (
    <>
        {eventCreated && <div className='event-created'>Event Created</div>}
        {error && <div className='error'>{error}</div> }
        <form 
        onSubmit={handleSubmit(submitForm)}
        className={'agent-form'}
        >
            {/* first name */}
            <label htmlFor='firstName'>First name</label>
            <input
                {...register('firstName')}
                id='firstName'
                className='form-control'
                type='text'
                placeholder='Joe'
                required
            />
            {errors.firstName && <span>This field is required</span>}
            {/* last name */}
            <label htmlFor='lastName'>Last Name</label>
            <input
                {...register('lastName')}
                id='lastName'
                className='form-control'
                type='text'
                placeholder='Persons'
                required
            />
            {errors.lastName && <span>This field is required</span>}
            {/*  photo url*/}
            <label htmlFor='photoUrl'>Photo Url</label>
            <input
                {...register('photoUrl')}
                id='photoUrl'
                className='form-control'
                placeholder='https://unsplash.com/photos/KBzb07tXYWA?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink'
                type='text'
            />
            {/* agent license */}
            <label htmlFor='agentLicence'>Agent License</label>
            <input
                {...register('agentLicence')}
                id='agentLicence'
                className='form-control'
                type='text'
                placeholder='123456'
                required
            />
            {errors.agentLicence && <span>This field is required</span>}
            {/* address */}
            <label htmlFor='address'>Address</label>
            <input
                {...register('address')}
                id='address'
                className='form-control'
                type='text'
                placeholder="555 Some Place Rd, Los Angeles, CA 90077"
                required
            />
            {errors.address && <span>This field is required</span>}
            {/* practice areas */}
            <label htmlFor='practiceAreas'>Practice Areas</label>
            <input 
                {...register('practiceAreas')}
                id='practiceAreas'
                className='form-control'
                type='text'
                placeholder='Los Angeles, San Francisco, Miami'
                required
            />
            {errors.practiceAreas && <span>This field is required</span>}
            {/* about me */}
            <label htmlFor='aboutMe'>About Me</label>
            <textarea
                {...register('aboutMe')}
                id='aboutMe'
                className='agent-text-area'
            />
            <button className='submit-agent' type='submit'>Submit</button>
        </form>
    </>
  );
};

export default AgentForm; 

【问题讨论】:

  • 在你的捕获中,从错误中返回了什么?因为这看起来就是问题所在。
  • 错误:网络错误

标签: reactjs typescript react-hook-form react-tsx


【解决方案1】:

看起来它是组件标记顶部附近的 error 引用:

  return (
    <>
        {eventCreated && <div className='event-created'>Event Created</div>}
        {error && <div className='error'>{error}</div> }
        {/*                          here ^^^^^ */}

正如它所说,“对象作为 React 子对象无效”并且error 是一个对象。引用error 的属性(例如error.message 之类的)或尝试error.toString()

【讨论】:

    【解决方案2】:

    看起来错误来自这一行:

            {error && <div className='error'>{error}</div> }
    

    因为{error} 不是一个有效的反应孩子。

    你也许可以改用这样的东西:

            {error && <div className='error'>{error.toString()}</div> }
    

    然后您应该能够看到真正的提交错误。

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 2020-11-18
      • 2019-12-26
      • 2016-09-21
      • 1970-01-01
      相关资源
      最近更新 更多