admin管理员组

文章数量:1292834

I'm trying to do some form validation in react, and I'm getting this error "Cannot read properties of null (reading "useState").

I've done a bit of research on SO, and others have resolved this by including an onChange which setups the useState, but this hasn't resolved it. Any idea why this is happening? Would it be because it's attempting to load the form, and the values are initially empty?

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

I'm trying to do some form validation in react, and I'm getting this error "Cannot read properties of null (reading "useState").

I've done a bit of research on SO, and others have resolved this by including an onChange which setups the useState, but this hasn't resolved it. Any idea why this is happening? Would it be because it's attempting to load the form, and the values are initially empty?

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
Share Improve this question edited May 27, 2022 at 10:12 jvs789789 asked May 27, 2022 at 10:10 jvs789789jvs789789 2031 gold badge3 silver badges12 bronze badges 1
  • 2 Hooks needs to be inside of the ponent, not outside of it – szczocik Commented May 27, 2022 at 10:11
Add a ment  | 

1 Answer 1

Reset to default 6

 const [form, setForm] = useState({});
    const [errors, setErrors] = useState({});
these needs to be inside the function.

本文标签: javascriptReactCannot read properties of null (quotreading useStatequot) errorStack Overflow