React新手求助:用户注册表单POST数据时handleSubmit无法触发
Hey there, let's break down why your handleSubmit isn't running as expected and fix those API post issues too!
First: Stop the Form's Default Submit Behavior
The biggest culprit here is your button inside the <form>—by default, buttons have a type="submit" value. When you click it, the browser triggers the form's native submit action, which refreshes the page immediately. This happens before your handleSubmit can even finish executing (or sometimes start at all!).
You have two simple fixes:
- Option 1: Add
type="button"to your button to bypass the default form submission:<button type="button" onClick={this.handleSubmit}>Register</button> - Option 2: Update
handleSubmitto accept the event parameter and block the default behavior:
You can keep your button as is, or explicitly sethandleSubmit = (e) => { e.preventDefault(); // Stops the page from refreshing console.log("handleSubmit()"); // ... rest of your code }type="submit"for clarity.
Second: Fix the Axios POST Request
Right now, you're wrapping your data in { body: JSON.stringify(data) }—this is incorrect for Axios. Axios automatically serializes JavaScript objects to JSON and sets the correct Content-Type header for you. Your current code sends a payload that looks like { body: "{"username":"...", ...}" }, which your backend won't parse correctly.
Update your Axios call to this:
axios.post( 'http://localhost:9000/api/registeruser', data // Send the plain data object directly ).then(res => console.log("Posted successfully!", res)) .catch(err => console.error("Post failed:", err)); // Add catch to debug API errors!
I added a .catch() here so you can see any API-related issues in the console—super useful for debugging.
Bonus: Simplify Your State Update Handlers
This isn't breaking your code, but you can clean up those repetitive change handlers into one function:
handleInputChange = (e) => { const { name, value } = e.target; this.setState({ [name]: value }); }
Then update your inputs to use a name attribute that matches your state keys:
<input name="name" value={this.state.name} onChange={this.handleInputChange} placeholder='Username' /><br /> <input name="display" value={this.state.display} onChange={this.handleInputChange} placeholder='Display Name' /><br /> <!-- Repeat this pattern for email and pswd inputs -->
This makes your code cleaner and easier to maintain.
Full Modified Code Snippet
Here's your component with all fixes applied (plus a small security tweak for the password input):
import React, { Component } from 'react'; import axios from 'axios'; import { Container, Row, Col } from 'reactstrap'; import NavBar from '../NavBar'; class RegistrationForm extends Component { constructor(props) { super(props) this.state = { name: '', display: '', email: '', pswd: '' } console.log("RegistrationForm constructor"); }; handleInputChange = (e) => { const { name, value } = e.target; this.setState({ [name]: value }); } handleSubmit = (e) => { e.preventDefault(); console.log("handleSubmit()"); const data = { username: this.state.name, displayname: this.state.display, email: this.state.email, password: this.state.pswd } axios.post( 'http://localhost:9000/api/registeruser', data ).then(res => console.log("Posted successfully!", res)) .catch(err => console.error("Error posting data:", err)); } render() { var logoImage = require('../../images/logo_v3_150.png'); return ( <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}> <Container> <Row> <img src={logoImage} width='150' height='184' /><br /> </Row> <Row> <form onSubmit={this.handleSubmit}> {/* Use form onSubmit for better UX (supports Enter key) */} <input name="name" value={this.state.name} onChange={this.handleInputChange} placeholder='Username' /><br /> <input name="display" value={this.state.display} onChange={this.handleInputChange} placeholder='Display Name' /><br /> <input name="email" value={this.state.email} onChange={this.handleInputChange} placeholder='Email' /><br /> <input name="pswd" value={this.state.pswd} onChange={this.handleInputChange} placeholder='Password' type="password" {/* Hides password input for security */} /><br /> <button type="submit">Register</button> </form> </Row> <Row> <NavBar /> </Row> </Container> </div> ); } } export default RegistrationForm;
I also switched to using onSubmit on the <form> instead of onClick on the button—this is the standard approach, as it also handles users submitting the form by pressing Enter.
Give these changes a go, and your form should submit without refreshing, plus send the correct data to your backend!
内容的提问来源于stack exchange,提问作者Val

