React 16.12.0 Hooks环境下如何对接登录API?
Troubleshooting Your React Login API Integration
Hey there! Let's get your login API working properly—you've already nailed the UI, so we just need to fix a few small issues in your API handling code. Here's what's going wrong and how to fix it:
Key Issues in Your Current Code
- Mismatched function parameters: You're passing
usernameandpasswordtoPostData, but the function only expects a singleuserDataobject. - Missing request body: The
bodyproperty in yourfetchcall is commented out—this is how you send the login credentials to the API. - Typo in Base URL: Your URL has a double slash (
//) between the domain and endpoint, which will cause invalid request routing.
Fixed Code Implementation
Updated VehiclesTable Component
import React, { useState } from "react"; import { Wrapper } from "./vehiclesTableStyles"; import { PostData } from "./postData"; function VehiclesTable() { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); // Add error state for user feedback const submitForm = async (e) => { e.preventDefault(); setError(""); // Clear previous errors before new request try { // Pass an object containing username and password to PostData const result = await PostData({ username, password }); console.log("Login success:", result); // Add your post-login logic here (e.g., store auth token, redirect to dashboard) } catch (err) { console.error("Login failed:", err); setError("Invalid username or password"); // Show user-friendly error message } }; return ( <Wrapper> <div className="search_box"> {/* Display error message if login fails */} {error && <p style={{ color: "red", marginBottom: "8px" }}>{error}</p>} <form onSubmit={submitForm}> <input name="name" type="text" placeholder="username" onChange={(e) => setUsername(e.target.value)} value={username} // Make input fully controlled /> <input name="password" type="password" placeholder="password" // Fixed placeholder text (was "search") onChange={(e) => setPassword(e.target.value)} value={password} // Make input fully controlled /> <input type="submit" value="login" /> </form> </div> </Wrapper> ); } export default VehiclesTable;
Updated PostData Function
export function PostData(userData) { // Fixed double slash in the base URL const BaseUrl = "https://reqres.in/api/login"; console.log("userData", userData); return new Promise((resolve, reject) => { fetch(BaseUrl, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", }, // Uncommented and added JSON-stringified body to send credentials body: JSON.stringify(userData), }) .then((response) => { // Handle non-success HTTP status codes (e.g., 400 Bad Request) if (!response.ok) { throw new Error("Login request failed"); } return response.json(); }) .then((responseJson) => { resolve(responseJson); }) .catch((error) => { reject(error); }); }); }
Additional Tips for Improvement
- Controlled Inputs: I added
valueprops to your inputs to make them fully controlled components—this ensures the component state always matches what's shown in the input fields. - Error Handling: Added an error state to display user-friendly feedback instead of just logging errors to the console.
- Async/Await: Switched from
.then()chains toasync/awaitin the submit handler for cleaner, more readable asynchronous code. - Status Code Validation: Added a check for
response.okto catch HTTP errors that wouldn't trigger thecatchblock by default (like invalid credentials returning a 400 status).
Test these changes with the sample credentials from reqres.in (e.g., eve.holt@reqres.in with password cityslicka) and your login flow should work smoothly!
内容的提问来源于stack exchange,提问作者Shahab Khan
相关产品推荐
相关产品推荐

