React HashRouter表单提交后URL出现多余参数问题求助
Hey there! Let's break down why this is happening and how to fix it properly:
This is actually a native HTML form behavior, not an issue with React HashRouter. When you submit a form without overriding its default behavior:
- Browsers default to using the
GETmethod for form submissions - All form inputs with a
nameattribute get their values appended to the URL as query parameters (the?State=Alabamapart you're seeing) - This happens regardless of React Router's setup, because it's the browser's built-in way to handle form submissions. Removing the
nameattribute works temporarily because the browser has no identifiers to attach to input values—but that's not a sustainable fix (you'll need those names to properly collect and send form data to your database).
The simplest and correct solution is to prevent the browser's default form submission action in your React handler. Here's how to do it:
- Add an
onSubmithandler to your form component - Call
e.preventDefault()at the start of the handler to stop the browser from adding those query parameters and refreshing the page
Example code:
import { useState } from 'react'; function ProfileForm() { const [formData, setFormData] = useState({ State: '' }); const handleInputChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; const handleSubmit = (e) => { e.preventDefault(); // 🔑 This stops the browser's default GET submission // Your existing logic to send formData to the database goes here console.log('Sending data:', formData); }; return ( <form onSubmit={handleSubmit}> <input type="text" name="State" value={formData.State} onChange={handleInputChange} placeholder="Enter state" /> <button type="submit">Submit</button> </form> ); }
method? If you tried setting method="post" on your form, the browser would send a POST request instead of appending parameters to the URL—but it would still refresh the page. You still need e.preventDefault() to keep the app single-page and avoid unwanted page reloads.
For more complex forms, libraries like React Hook Form handle the default behavior blocking automatically, along with data collection and validation. Here's a quick example:
import { useForm } from 'react-hook-form'; function ProfileForm() { const { register, handleSubmit } = useForm(); const onSubmit = (data) => { // Send data to database—no need to call e.preventDefault() here! console.log('Sending data:', data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register('State')} placeholder="Enter state" /> <button type="submit">Submit</button> </form> ); }
内容的提问来源于stack exchange,提问作者in43sh

