我相信這是一個簡單的邏輯,但由于我仍在學習,我在實作它時遇到了一些困難。
在我的專案的登錄頁面上,我獲得了發布請求后誰登錄的資料。在用戶中,我有“型別”欄位。只有兩種型別的用戶。
我想要的是,如果用戶的型別為 A,他將被重定向到“主頁”頁面,如果他是 B 型別,他將轉到“主”頁面。如果您還沒有定義型別值,請轉到“用戶型別”頁面。
我在這里寫了這個邏輯,但它不起作用。有誰能夠幫我?
這是我的代碼
async function onFinish(values) {
let axiosConfig = {
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
},
};
Axios.post(
` /login`,
{
email: values.email,
senha: values.password,
},
axiosConfig
)
.then((resp) => {
var name = resp?.data[0]?.prinom;
var userId = resp?.data[0]?.id;
var prodUser = resp?.data[0];
localStorage.setItem("prodUser", JSON.stringify(prodUser));
//here's the part i need help
if (!resp?.data[0]?.tipo) history.push("/tipodeusuario");
resp?.data[0]?.tipo === "pac" ? history.push("/homepac") : history.push("/home");
})
uj5u.com熱心網友回復:
首先,您需要將您的回應存盤在一個變數中以獲得可讀的代碼,因此:
let apiResp = respoone.data.tipo;
if (apiResp === A){
history.push('/HomePage')
}if(apiResp === B) {
history.push('/MainPAge')
}else {
history.push('/userType')
}
您還可以使用“切換案例”方法。
或者我不推薦的條件(三元)運算子,因為它會使您的代碼可讀性降低。
uj5u.com熱心網友回復:
找到用戶型別(即 A 或 B)后,您可以簡單地為 window.location
這是一些偽代碼
function getUserType(AorB){
//Get user type
return AorB;
}
//Store urls in a variable
let url = (getUserType('A') == 'A')? './UrlForUserTypeA':'./UrlForUserTypeB';
//Redirect
console.log('Redirecting...');
window.location = url;
希望這就是你所需要的
uj5u.com熱心網友回復:
我在這里發布答案是因為我沒有足夠的聲譽來發表評論。
由于您使用的是 React.js,您可以將用戶型別存盤在一個狀態中,并有條件地呈現與該狀態匹配的組件。
function MyApp() {
const [userType, setUserType] = React.useState('')
async function onFinish(values) {
Axios.post().then((response) => {
setUserType(reponse.data[0].tipo)
})
}
return (
<>
{userType === 'A'
? <RenderPageComponentA />
: userType === 'B'
? <RenderPageComponentB />
: <RenderPageComponentUserType />
}
</>
)
}
這個庫可能對你有幫助:https : //v5.reactrouter.com/web/guides/quick-start
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/381484.html
標籤:javascript 反应
