React新手使用多输入表单时遇TypeError: Cannot read property 'email' of undefined错误求助
Hey there! Let's break down what's causing this error and fix it up for you.
The Main Culprit: Incorrect useState Destructuring
First off, the big issue here is how you're destructuring the useState hook. React's useState returns an array (not an object), so you need to use array destructuring instead of object destructuring. Your current code:
const{forInp,setForm}=useState({ email:"abc@gmail.com", password:"" });
This tries to pull forInp and setForm as properties from an object, but since useState gives you an array, forInp ends up being undefined. That's why you get the error when trying to access forInp.email—you're trying to read a property from an undefined value.
Secondary Issue: Broken handleSubmit Function
Your handleSubmit function is also problematic. Right now, it's setting the form state to {[event.target.name]:""}, but event.target here is the <form> element, which doesn't have a name attribute. This would overwrite your entire form state with an empty object (or an object with a random empty property), leading to more errors down the line.
Corrected Code
Here's the fixed version of your component with explanations of the changes:
import React from 'react'; import { useState } from 'react'; export default function SignIn() { // Fixed: Use array destructuring for useState const [formInp, setForm] = useState({ email: "abc@gmail.com", password: "" }); function handleChange(event) { setForm({ ...formInp, [event.target.name]: event.target.value }); } function handleSubmit(event) { event.preventDefault(); // Fixed: Reset form to initial state instead of overwriting it incorrectly setForm({ email: "abc@gmail.com", password: "" }); // Alternatively, if you want to clear both fields completely: // setForm({ email: "", password: "" }); } return ( <div> <form onSubmit={handleSubmit}> <input type="email" name="email" value={formInp.email} placeholder="Email" onChange={handleChange} /> <input type="password" name="password" value={formInp.password} placeholder="Password" onChange={handleChange} /> {/* Don't forget to add a submit button! */} <button type="submit">Sign In</button> </form> </div> ); }
Key Changes Made:
- Swapped
const{forInp,setForm}toconst [formInp, setForm]to use proper array destructuring foruseState. - Fixed the
handleSubmitfunction to reset the form state correctly (either back to the initial email value or completely empty, depending on your needs). - Added a submit button since your form didn't have one—you need this to trigger the
onSubmithandler!
That should resolve the "Cannot read property 'email' of undefined" error and get your sign-in form working as expected.
内容的提问来源于stack exchange,提问作者Abhijeet

