![](/img/trans.png)
[英]Error "TypeError: Cannot read property 'email' of undefined" using AngularJS and Ionic
[英]TypeError: Cannot read property 'email' of undefined while using form with Multiple Inputs
我是 React 的初学者,遇到了一些问题。我收到错误消息“TypeError: Cannot read property 'email' of undefined”。 请在下面找到错误截图:-
登录.js
import React from 'react';
import {useState} from 'react';
export default function SignIn()
{
const{forInp,setForm}=useState({
email:"abc@gmail.com",
password:""
});
function handleChange(event)
{
setForm({
...forInp,
[event.target.name]:event.target.value});
}
function handleSubmit(event)
{
event.preventDefault();
setForm({[event.target.name]:""});
}
return(
<div>
<form onSubmit={handleSubmit}>
<input type="email" name="email" value={forInp.email} placeholder="Email" onChange={handleChange}/>
<input type="Password" name="password" value={forInp.password} placeholder="Password" onChange={handleChange}/>
</form>
</div>
);
}
修改了使用 USeState 正确返回格式的代码。 而不是 Object 它返回数组。 以下是codeandbox链接:
https://codesandbox.io/s/trusting-elbakyan-9h2sn?file=/src/SignIn.js
import React from "react";
import { useState } from "react";
export default function SignIn() {
const [ forInp, setForm ] = useState({
email: "abc@gmail.com",
password: ""
});
function handleChange(event) {
setForm({
...forInp,
[event.target.name]: event.target.value
});
}
function handleSubmit(event) {
event.preventDefault();
setForm({ [event.target.name]: "" });
}
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="email"
name="email"
value={forInp.email}
placeholder="Email"
onChange={handleChange}
/>
<input
type="Password"
name="password"
value={forInp.password}
placeholder="Password"
onChange={handleChange}
/>
</form>
</div>
);
}
The correct way to useState is like
const[forInp,setForm]=useState({
email:"abc@gmail.com",
password:""
});
we need to set two variable in array and assigned this array from useState
Here is reference link
https://reactjs.org/docs/hooks-state.html
你需要改变这个:
const{forInp,setForm}=useState({
email:"abc@gmail.com",
password:""
});
对此:
const [ forInp, setForm ] = useState({
email: "abc@gmail.com",
password: ""
});
解释:
React.useState 返回[ state, function ]
的数组,而不是 Object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.