我如何将用户重定向到他以前所在的页面(让我们说一个详细页面)或他在react中成功验证后试图访问的页面,就像在django中使用常规模板的request.GET.next一样,我使用formik和django knox认证为我的服务器端。我知道的useLocation()钩子,如果是这样,我怎么能存储前一个或下一个url路径在useLocation状态动态。
AUTH.JS
const {setIsLoggedIn,setUserData,isloggedIn,}=useContext(AuthContext)
const location=useLocation()
// console.log(location.state.from)
const loginformik=useFormik({
initialValues:{
// firstName:"",
// lastName:"",
email:"",
password:"",
},
validationSchema:Yup.object({
email:Yup.string().email('invalid email address').required(),
password:Yup.string().min(6,'password must be more than characters').required(),
}),
onSubmit:(values=>{
fetch('http://127.0.0.1:8000/auth/login',{
method:'POST',
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/form-data',
},
body: JSON.stringify(values)
}).then(res=>res.json()).then(data=>{
console.log(data)
localStorage.setItem('token',data.token)
setUserData(data.user)
setIsLoggedIn(true)
if (data.status=== 202){
setIsLoggedIn(true)
}
})
})
})
DETAIL.js
const getPosts=async ()=> {
const token=localStorage.getItem('token')
console.log(token)
const response= await fetch(`http://127.0.0.1:8000/${id}/`,{
method:'GET',
headers:{
'Accept': 'application/json',
'Authorization':`Token ${token}`,
'Content-Type': 'application/json'
}
})
console.log(response.url)
if (response.status===401){
navigate(`/auth?login`)
localStorage.setItem('next_url',response.url)
}
const data=await response.json()
setPost(data.music)
}
在Detail
组件中使用useLocation
钩子来传递当前位置,以便Auth
组件知道它可以重定向到哪里。
详细
import { ..., useLocation, useNavigate } from 'react-router';
...
const navigate = useNavigate();
const location = useLocation();
...
const getPosts = async () => {
const token = localStorage.getItem('token');
console.log(token);
const response = await fetch(`http://127.0.0.1:8000/${id}/`, {
method:'GET',
headers:{
'Accept': 'application/json',
'Authorization':`Token ${token}`,
'Content-Type': 'application/json'
}
});
console.log(response.url);
if (response.status === 401) {
navigate(
"/auth?login",
{
state: { from: location }, // <-- pass current location
replace: true
}
);
localStorage.setItem('next_url',response.url);
}
const data = await response.json();
setPost(data.music);
}
身份验证
import { ..., useLocation, useNavigate } from 'react-router';
...
const { setIsLoggedIn, setUserData, isloggedIn } = useContext(AuthContext);
const navigate = useNavigate();
const location = useLocation();
const loginformik = useFormik({
initialValues: {
// firstName:"",
// lastName:"",
email:"",
password:"",
},
validationSchema: Yup.object({
email: Yup.string()
.email('invalid email address')
.required(),
password: Yup.string()
.min(6,'password must be more than characters')
.required(),
}),
onSubmit: values => {
fetch('http://127.0.0.1:8000/auth/login', {
method:'POST',
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/form-data',
},
body: JSON.stringify(values)
})
.then(res => res.json())
.then(data => {
console.log(data);
localStorage.setItem('token', data.token);
setUserData(data.user);
setIsLoggedIn(true);
if (data.status === 202) {
setIsLoggedIn(true);
}
// Redirect back to previous location, or home
const { state } = location;
const { from } = state || { from: { pathname: "/" } };
navigate(from, { replace: true });
});
},
});
Usereact router Dom 6. 它有useNavigation钩子效果很好。你可以用编程的方式进行导航。