React PreventDefault 函数不会停止重新加载表单页面

问题描述 投票:0回答:1

我正在创建一个 React 上下文来解码 jwts 并管理用户的登录功能。后端是使用django编写的。

<<<<< Login.jsx >>>>>

import React, { useContext } from 'react'
import AuthContext from '../context/AuthContext'

function Login() {

   let {loginUser} = useContext(AuthContext)

return (
     <form onSubmit={loginUser}>
        Email address: <input type=email name=email />
        Password: <input type=password name=password />

       <Button type="submit" />
     </form>
  )
}
export default Login

从上面的jsx代码中,我想触发AuthContext.jsx文件中的loginUser函数,保存在'../context/AuthContext'中,并将电子邮件和密码值获取到AuthContext文件中。

<<<<< AuthContext.jsx >>>>>

import { createContext } from "react"
import { useNavigate } from 'react-router-dom'

const AuthContext = createContext()

export default AuthContext

export const AuthProvider = ({children}) => {

  const loginUser = async (e)=> {
        e.preventDefault()

     let response = await fetch('http://127.0.0.1:8000/api/token/', {
            method: 'POST',
            headers: {
                'Content-Type':'application/json',
            },
            body:      JSON.stringify({'email':e.target.email.value,'password':e.target.password.value})
        })
  }
    return(
        --- some code ---
    )
}

这些是简化的代码。

我在这里面临的问题是,我无法从登录表单中获取数据,因为 loginUser 函数中的 PreventDefault() 不起作用,并且每次提交表单时都会使登录表单刷新。登录表单网址变为“http://localhost:5173/employee/login + login?email=c%40c.com&password=c&submit=Log+in”。

有没有其他方法可以让我不重新加载登录表单页面并成功将数据获取到AuthContext页面?

由于我编写代码的方式,OnClick 函数无法在按钮上使用。我无法想出其他方法来实现这一目标。

html reactjs forms react-hooks react-context
1个回答
0
投票
我测试了你分享的2个页面,看起来你做对了。

只要执行

e.preventDefault()

 就会停止重新加载,所以我猜测为什么会发生这种情况。您说您正在使用 Django 作为后端,因此您返回的响应可能使浏览器重新加载页面。

据我所知,如果您返回带有一些状态代码的 JsonResponse ,应该没问题

Here中,您可以评论和取消评论e.preventDefault()

行,您会注意到,只要取消评论,页面就不会重新加载

© www.soinside.com 2019 - 2024. All rights reserved.