我想在成功登錄主頁后重定向用戶,但沒有任何效果。這是我的 Login.js 組件另外,我無法在基于類的組件中獲取引數 URL,我被迫使用功能組件,我let params=useParams();
用來獲取 URL 引數
function Login(props) {
const sendSms = async (e=null) => {
if (typeof(securityCode) !=='undefined' && securityCode.toString().length === 6) {
const response = await fetch('http://localhost:8000/api/login/' ,{
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
mobile,
securityCode
})
});
const data = await response.json();
let result=data.result;
let message=data.message;
if (result === 'success') {
clearInterval(sms_interval);
setToken(data.data);
return navigate("/", { replace: true }); //important
return false;
} else {
setAlertClass('alert-danger');
setAlertMessage(message);
}
return false;
}
fetch('http://localhost:8000/api/send_sms/' ,{
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
mobile
})
})
.then(response => response.json())
.then(data => {
let result=data.result;
let message=data.message;
if (result === 'success') {
let sms_timer = 120;
setSmsInteral(setInterval(function () {
if (sms_timer > 0) {
}, 1000)
);
} else {
}
});
return false;
}
}
uj5u.com熱心網友回復:
所述useHistory
鉤不再存在與之反應路由器6。
嘗試使用useNavigate
鉤子并將函式轉換為使用async / await
:
import { useNavigate } from "react-router-dom";
function Login(props) {
const navigate = useNavigate();
const verify = async (e = null) => {
try {
const response = await fetch("http://localhost:8000/api/login/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
mobile,
securityCode,
}),
});
const data = await response.json();
let result = data.result;
let message = data.message;
if (result === "success") {
clearInterval(sms_interval);
setToken(data.data);
navigate("/");
} else {
sms_alert_element.classList.add("alert-danger");
sms_alert_element.innerText = message;
}
return false;
} catch (err) {
console.log(err);
}
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/397083.html