我正在製作一個註冊頁面,但似乎不明白為什麼它不起作用。
編輯:更新了程式碼以刪除 userObject。仍然無法取得將資料實際發佈到我的 json 檔案的程式碼。
新程式碼:
import { useState } from "react"; const Signup = () => { const [formData, setFormData] = useState({ email: "", password: "", confirmPassword: "", }); const handleInputChange = (event) => { setFormData({ ...formData, [event.target.name]: event.target.value, }); }; console.log(formData) const handleSubmit = (event) => { event.preventDefault(); console.log(formData); fetch("http://localhost:8000/users", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(formData), }).then(() => { window.location.href = "/profile"; }); }; return ( <div> <h2>Sign up</h2> <form onSubmit={handleSubmit}> <div> <label>Email:</label> <input type="email" name="email" value={formData.email} onChange={handleInputChange} required /> </div> <div> <label>Password:</label> <input type="password" name="password" value={formData.password} onChange={handleInputChange} required /> </div> <div> <label>Confirm Password:</label> <input type="password" name="confirmPassword" value={formData.confirmPassword} onChange={handleInputChange} required /> </div> <button type="submit">Sign up</button> </form> </div> ); }; export default Signup;
舊程式碼:
import { useState } from "react"; const Signup = () => { const [formData, setFormData] = useState({ email: "", password: "", confirmPassword: "", }); const handleInputChange = (event) => { setFormData({ ...formData, [event.target.name]: event.target.value, }); }; console.log(formData) const handleSubmit = (event) => { event.preventDefault(); const userObject = { email: formData.email, password: formData.password, }; fetch("http://localhost:8000/users", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(userObject), }).then(() => { window.location.href = "/profile"; }); }; console.log(userObject) return ( <div> <h2>Sign up</h2> <form onSubmit={handleSubmit}> <div> <label>Email:</label> <input type="email" name="email" value={formData.email} onChange={handleInputChange} required /> </div> <div> <label>Password:</label> <input type="password" name="password" value={formData.password} onChange={handleInputChange} required /> </div> <div> <label>Confirm Password:</label> <input type="password" name="confirmPassword" value={formData.confirmPassword} onChange={handleInputChange} required /> </div> <button type="submit">Sign up</button> </form> </div> ); }; export default Signup;
當我console.log formData時,它正在接收數據,但是當我嘗試console.log userObject時,它返回為未定義。我已經在谷歌上搜索了幾個小時,檢查了這裡類似問題的解決方案,並嘗試了不同的方法,但似乎無法將其保存到我的 json 文件中。希望以新的眼光我能得到一些幫助。謝謝!
這是正常的。很遺憾地告訴您,您的
console.log
函數沒有在正確的時間呼叫!您的程式碼應該是:
就像支出者所說: