我有一個問題,在我的注冊頁面上,回應顯示用戶已經存在,但是繼續到主頁,就像創建了一個新的登錄名一樣。如果用戶存在,我希望這回到登錄頁面。我曾嘗試添加一個 if else 塊,但這沒有用。我不確定我做錯了什么。

const onSubmitForm = async (e: any) => {
e.preventDefault();
try {
const body = { email, password, name };
const response = await fetch('http://localhost:5000/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
const parseRes = await response.json();
console.log(parseRes);
localStorage.setItem('token', parseRes);
// history.push('/home');
props.setAuth(true);
} catch (error) {
let errorMessage = 'Server error';
if (error instanceof Error) {
errorMessage = error.message;
}
console.error(errorMessage);
}
// eslint-disable-next-line no-lone-blocks
{
toggleSignup();
}
};
uj5u.com熱心網友回復:
如果您想根據服務器的回應有條件地轉到某個頁面,那么您是正確的,一個簡單的方法是使用if/else陳述句。
這是一個簡單的例子:
const onSubmitForm = async (e: any) => {
e.preventDefault();
try {
const body = { email, password, name };
const response = await fetch('http://localhost:5000/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
const parseRes = await response.json();
// In YOUR code, you don't check the value of parseRes so your code goes straight to history.push('/home').
// You want to check the value of parseRes and conditionally go to a certain page based on the value
if (parseRes === 'User already registered') {
history.push('/login');
}
else {
localStorage.setItem('token', parseRes);
history.push('/home');
}
props.setAuth(true);
} catch (error) {
let errorMessage = 'Server error';
if (error instanceof Error) {
errorMessage = error.message;
}
console.error(errorMessage);
}
// eslint-disable-next-line no-lone-blocks
{
toggleSignup();
}
};
您當前的代碼不會檢查 的值parseRes并且將始終執行,history.push('/home')因為它是下一行。
順便提一下,不建議檢查“用戶已經注冊”的值,我只是用它來讓您知道該怎么做。通常,您需要檢查 HTTP 回應代碼(即 200、400、401 等)或檢查一些回傳的 JSON 值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/328964.html
