當我填寫表單輸入時,它會顯示我以前的值,例如,如果我輸入 1,它會顯示“”,然后如果我輸入 2,它會顯示“1”,就像它顯示先前狀態的值一樣。我不知道如何解決它。感謝任何幫助
const Create = () => {
let history = useHistory();
let [person, setPerson] = useState({
name:"",
about:"",
email:"",
image:"",
})
let createPerson = async () => {
fetch(`/api/person-create/`, {
method: "POST",
headers: {
"content-type": 'application/json'
},
body: JSON.stringify(person)
})
}
let handleChange = (e) => {
setPerson({...person, [e.target.id]: e.target.value})
console.log(person)
}
return (
<form>
<div>
<h2 className="notes-title" style={{marginLeft:'700px'}}>
<button onClick={() => history.push('/')} className="btn btn-primary mt-4">
❮ Back
</button>
</h2>
<h2 className="mt-4 mb-4" style={{width: '600px', marginLeft:'700px'}}>
New Person
</h2>
<div className="form-group" style={{width: '600px', marginLeft:'700px'}}>
<label>Name</label>
<input onChange={handleChange} className="form-control" id="name" placeholder="Enter Name" value={person.name} />
</div>
<div className="form-group" style={{width: '600px', marginLeft:'700px'}}>
<label for="exampleInputEmail1">About</label>
<textarea style={{height: '250px'}} className="form-control" id="about" placeholder="Tell us somthing about yourself" value={person.about} />
</div>
<div className="form-group" style={{width: '600px', marginLeft:'700px'}}>
<label>Email</label>
<input className="form-control" id="email" placeholder="Enter Email" value={person.email} />
</div>
<div className="custom-file mt-3" style={{marginLeft:'700px'}}>
<input type="file" className="custom-file-input" id="image" value={person.image} />
<label className="custom-file-label" for="customFile">Choose file</label>
</div>
<button type="submit" style={{marginLeft:'700px'}} className="btn btn-primary mt-4">Submit</button>
</div>
</form>
)
}
export default Create
我知道它正在發生,因為狀態只會在我在表單中放入一些東西后才更新,但無法找到修復方法。
uj5u.com熱心網友回復:
setPerson異步功能,您必須檢查人員更新useEffect。檔案
useEffect(() => {
console.log("correct", person);
}, [person]);
演示
uj5u.com熱心網友回復:
Previous State更新狀態時最好使用。請按照以下代碼:
let handleChange = (e) => {
setPerson( (per) => ({...per, [e.target.id]: e.target.value}));
console.log(person)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/366639.html
標籤:javascript 反应 形式
