我想在成功登录主页后将用户重定向到主页,但没有任何效果。
这是我的 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;
}
}
最佳答案
React Router 6 中不再存在 useHistory
钩子(Hook)。
尝试使用useNavigate
钩子(Hook)并将函数转换为使用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);
}
};
}
关于reactjs - 在 React Router 6 和 ReactJS 17 中重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70484831/