React - 无法读取 null 的属性(“读取 useState”)错误

2024-01-05

我试图在 React 中进行一些表单验证,但收到此错误“无法读取 null 的属性(读取“useState”)。

我对 SO 做了一些研究,其他人已经通过包含一个设置 useState 的 onChange 解决了这个问题,但这并没有解决它。知道为什么会发生这种情况吗?是否是因为它正在尝试加载表单,并且值最初为空?

import React from 'react'
import Form from 'react-bootstrap/Form'
import { Button } from 'react-bootstrap'
import { Container } from 'react-bootstrap'
import { useState } from 'react';


const [form, setForm] = useState({});
const [errors, setErrors] = useState({});  // state is called in handleSubmit function

const setField = (field, value) => {
  setForm({
    ...form,
    [field]: value
  })
  // Check and see if errors exist, and remove them from the error object:
  if (!!errors[field]) setErrors({
    ...errors,
    [field]: value
  })
}

const findFormErrors = () => {
  const { email, password } = form;
  const newErrors = {}
  // email errors
  if (!email || email === "") newErrors.email = "cannot be blank";
  else if (email.length > 40) newErrors.email = "too long";

  if (!password || password === "") newErrors.password = "can't be an empty password";
  else if (password.length < 5) newErrors.password = "password is not long enough";

  return newErrors  // essentially returning the new errors, empty object

}

const handleSubmit = e => {
  e.preventDefault()

  const newErrors = findFormErrors();

  if (Object.keys(newErrors).length > 0) {
    setErrors(newErrors)
  } else {
    alert("thanks for signing up!");
  }
}

const theForm = () => {
  return (
    <Container>
      <Form className="reduceForm">
        <Form.Label className="contact">Contact Me</Form.Label>
        <Form.Group className="mb-3" controlId="formBasicEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control type="email" placeholder="Enter email"
            onChange={e => setField('email', e.target.value)}
            isInvalid={!!errors.name} />
          <Form.Control.Feedback type='invalid'>
            {errors.name}
          </Form.Control.Feedback>
        </Form.Group>
        
        <Form.Group className="mb-3" controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control type="password" placeholder="Password"
            onChange={e => setField('password', e.target.value)}
            isInvalid={!!errors.name} />
          <Form.Control.Feedback type='invalid'>
            {errors.name}
          </Form.Control.Feedback>
        </Form.Group>
        <Button variant="primary" type="submit">
          Submit
        </Button>
      </Form>
    </Container>
  )
}

export default theForm

 const [form, setForm] = useState({});
    const [errors, setErrors] = useState({});
these needs to be inside the function.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React - 无法读取 null 的属性(“读取 useState”)错误 的相关文章

随机推荐