用户在React中进行身份验证后页面重定向

b5lpy0ml  于 2023-01-21  发布在  React
关注(0)|答案(2)|浏览(134)

我怎样才能重定向一个用户到他之前所在的页面(比如说一个详细页面)或者他在react中成功验证后试图访问的页面就像django中的request.GET.next使用常规模板一样,我在服务器端使用formik和django knox验证。我知道useLocation()钩子,如果是这样,我如何在uselocation状态中动态地存储前一个或下一个url路径。

授权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)
            }
        })
        
    })
})

详图.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)

}
ftf50wuq

ftf50wuq1#

使用react router Dom 6。它有useNavigation钩子,运行良好。你可以通过编程来导航。

7ajki6be

7ajki6be2#

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 });
      });
  },
});

相关问题