基本上我想要做的是在用戶提交注冊并從包含上述字串的 API 成功回應后,將最初顯示“歡迎”的文本更改為“你好 {user},請檢查您的電子郵件以進行驗證” .
然而,在回傳注冊函式(發布并接收來自 API 呼叫的回傳)之前,回應變數似乎設定為未定義,因此 Setmessage 將訊息變數設定為未定義,而不是僅在幾個之后出現的回傳字串幾秒鐘后。
研究了很多關于useEffect、回呼函式和AJAX知識的方法,但是還是不太明白自己的代碼需要做什么。
export default function Signup() {
const [message, Setmessage] = useState('Welcome')
async function handleSubmit(e){
const response = await signup(usernameRef.current.value, emailRef.current.value, passwordRef.current.value)
Setmessage(response)
}
return(
{message}
//a submission form that invokes handlesubmit
)
}
//sign up function from another component
function signup(name, e, p){
axios.post('/register', {
username: name,
email: e,
password: p
})
.then(function (response) {
console.log(response.data[0])
return response.data[0];//"dear user, please check etc..."
})
}
//api using Fastapi
@app.post("/register")
async def user_register(user: UserIn_Pydantic):
user_info = user.dict(exclude_unset=True) #user changed into dictionary format
user_info["password"] = get_password_hash(user_info["password"]) #we create new password field and save hashed password in
#exclude_unset: whether fields which were not explicitly set when creating the model should be excluded from the returned dictionary
user_obj = await User.create(**user_info) #stores it in database table user
new_user = await user_pydantic.from_tortoise_orm(user_obj)#convert userobj into pydantic model
await simple_send(email=[new_user.email], instance=new_user)
return {
"{}, please check you email for verification link, {}".format(new_user.username,new_user.password)
}
uj5u.com熱心網友回復:
await運算子用于等待Promise。
所以為了await signup()in handleSubmit,signup函式本身需要回傳一個 Promise。例如
function signup(name, e, p) {
return axios
.post("/register", {
username: name,
email: e,
password: p,
})
.then(function (response) {
console.log(response.data[0]);
return response.data[0]; //"dear user, please check etc..."
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/492842.html
標籤:javascript 反应 阿贾克斯 使用状态
上一篇:使用ajax的資料沒有出現在前端
