React多输入框提交DRF后端异常:输入值同步无法区分
Hey, I see exactly what's causing your issue—your handleChange function is hardcoding updates to both project_name and project_name_RnD with the same input value, regardless of which field you're typing into. That's why both inputs end up with identical text. Let's break down the fixes step by step:
1. Fix the handleChange Function to Target Specific Fields
Instead of manually setting each state property, use the input's name attribute to dynamically update the correct field in your activeItem state. This way, each input only updates its corresponding state key:
handleChange(e) { const { name, value } = e.target; this.setState(prevState => ({ activeItem: { ...prevState.activeItem, [name]: value // Dynamically update the field matching the input's name } })); }
2. Align Input name Attributes with State Keys
Right now your inputs have name values that don't match the keys in your activeItem state. Let's fix that to ensure the handleChange function maps correctly:
<input onChange={this.handleChange} type='text' id='virtual_project' name='project_name' // Matches state key "project_name" value={this.state.activeItem.project_name} placeholder='Project Name' /> <input onChange={this.handleChange} type='text' id='virtual_project_RnD' name='project_name_RnD' // Matches state key "project_name_RnD" value={this.state.activeItem.project_name_RnD} placeholder='Project Name RnD' />
3. Wrap Inputs in a Form & Bind the Submit Handler
Your submit button won't trigger any action right now because it's not inside a <form> with an onSubmit handler. Let's add that and implement the handleSubmit function to send data to your DRF backend:
render() { return ( <div> <form onSubmit={this.handleSubmit}> {/* Your two inputs go here */} <input onChange={this.handleChange} type='text' id='virtual_project' name='project_name' value={this.state.activeItem.project_name} placeholder='Project Name' /> <input onChange={this.handleChange} type='text' id='virtual_project_RnD' name='project_name_RnD' value={this.state.activeItem.project_name_RnD} placeholder='Project Name RnD' /> <button type='submit'>Add</button> {/* Use button for better semantic HTML */} </form> </div> ); } // Implement handleSubmit to send data to your DRF endpoint handleSubmit(e) { e.preventDefault(); // Prevent default form page reload const { activeItem } = this.state; // Send POST request to DRF fetch('YOUR_DRF_API_ENDPOINT', { // Replace with your actual API URL method: 'POST', headers: { 'Content-Type': 'application/json', // Include CSRF token (required for Django by default) 'X-CSRFToken': this.getCSRFToken() }, body: JSON.stringify(activeItem) }) .then(response => response.json()) .then(data => { console.log('Submission successful:', data); // Refresh project list and reset form state this.fetchVirtualProjects(); this.setState({ activeItem: { id: null, project_name: '', project_name_RnD: '' } }); }) .catch(error => { console.error('Submission error:', error); }); } // Helper function to get CSRF token from cookies getCSRFToken() { const value = `; ${document.cookie}`; const parts = value.split(`; csrftoken=`); if (parts.length === 2) return parts.pop().split(';').shift(); }
Final Quick Checks
- Ensure your DRF serializer (in
serializers.py) includes bothproject_nameandproject_name_RnDfields so the backend can accept the data. - Verify your DRF view allows POST requests and has appropriate permissions configured.
That should fix the duplicate input values and get your multi-field form submitting correctly to your DRF backend!
内容的提问来源于stack exchange,提问作者pipikej

