React.js中使用Axios实现登录表单API调用求助(附可用jQuery代码)
React 登录表单实现(适配原jQuery代码逻辑)
以下是完全匹配你提供的jQuery功能的React版本,使用Axios调用API,同时保留原页面的Tailwind样式:
import React, { useState } from 'react'; import axios from 'axios'; function LoginForm() { // 管理表单输入与提示消息的状态 const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [message, setMessage] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); // 阻止表单默认提交行为 setMessage(''); // 清空历史提示 try { // 对参数进行URL编码,避免特殊字符导致请求异常 const encodedUsername = encodeURIComponent(username); const encodedPassword = encodeURIComponent(password); const apiUrl = `http://portal.mashitec.com/SalesWebApi/api/User1/?login=${encodedUsername}&passw=${encodedPassword}`; // 发送POST请求 const response = await axios.post(apiUrl); // 验证API响应结果 if (response.data === username) { setMessage('Authorized'); } else { setMessage('Not Authorized'); } } catch (error) { // 捕获并显示请求错误 setMessage(`Error: ${error.message}`); } }; return ( <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 py-2 sm:px-6 lg:px-8"> <div className="max-w-md w-full space-y-8"> <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900"> Login Form </h2> <form onSubmit={handleSubmit} className="mt-8 space-y-6"> <div> <label htmlFor="username" className="sr-only">Username:</label> <input type="text" id="username" name="username" required className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Username" value={username} onChange={(e) => setUsername(e.target.value)} /> </div> <div> <label htmlFor="password" className="sr-only">Password:</label> <input type="password" id="password" name="password" required className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> </div> <button type="submit" className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" > Login </button> </form> <p className="mt-2 text-center text-sm text-gray-600">{message}</p> </div> </div> ); } export default LoginForm;
核心改动说明
状态管理:
- 用React的
useState钩子替代jQuery的DOM查询,将输入框值与组件状态绑定,实现数据驱动视图。 - 每个输入框通过
value(绑定状态)和onChange(更新状态)实现双向同步。
- 用React的
表单提交:
- 在表单元素上绑定
onSubmit事件,替代jQuery的$('#loginForm').submit()监听。 - 同样使用
e.preventDefault()阻止浏览器默认提交行为。
- 在表单元素上绑定
API请求:
- 用Axios的
axios.post()替代$.ajax(),采用async/await语法简化异步代码。 - 保留原有的
encodeURIComponent参数编码逻辑,避免特殊字符引发的请求错误。 - 用
try/catch捕获请求异常,替代jQuery的error回调。
- 用Axios的
提示消息更新:
- 通过
setMessage更新状态来修改提示文本,替代直接操作DOM的$('#message').text()。
- 通过
常见报错解决方案
- Axios未安装:执行
npm install axios或yarn add axios安装依赖。 - 跨域错误:若浏览器报CORS异常,需确认API是否允许当前域名跨域请求,或在本地开发时配置代理(如Create React App可在
package.json添加proxy字段)。 - 输入无法同步:检查输入框是否同时设置了
value和onChange,确保状态与视图双向绑定。
内容的提问来源于stack exchange,提问作者ZarakKahn
相关产品推荐
相关产品推荐

