![](/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.