React中Axios Post方法失效求助:求可行解决方案
Let's break down the issues with your code and fix them step by step:
1. Incorrect State Update for the dogName Array
Array.push() mutates the original React state array (a big no-no!) and returns the new length of the array, not the updated array itself. So when you run this.setState({ dogName: this.state.dogName.push(newDog) }), you're actually setting dogName to a number instead of the array of dogs. This breaks both your state and the subsequent POST request.
Fix this by using immutable updates with the spread operator, and use functional setState to avoid stale state issues:
// Replace this flawed line: this.setState({ dogName: this.state.dogName.push(newDog) }) // With this: this.setState(prevState => ({ dogName: [...prevState.dogName, newDog] }))
2. Wrong Data Sent in the Axios POST Request
You're sending the entire dogName array to your backend, but most POST endpoints for creating new resources expect a single object (the new dog entry), not the full collection. Your backend is likely configured to add one dog at a time, not replace the entire database.
Update your Axios call to send only the new dog object:
// Replace this: await axios.post('http://localhost:3000/dogs', this.state.dogName) // With this: await axios.post('http://localhost:3000/dogs', newDog)
3. Unnecessary ID Updates in the Dogue Component
Right now, you generate a new id every time the user types a character in the input. This is unnecessary—you only need to create the ID once when the form is submitted. Move the ID generation to the handleSubmit method:
// Updated Dogue component import React from 'react' class Dogue extends React.Component { constructor(props){ super(props) this.state = { nameInput:'' } // Remove id from local state this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } handleChange(e) { this.setState({ nameInput: e.target.value }) // Only update input value } handleSubmit(e){ e.preventDefault() const newId = Date.now() // Generate ID only on submit this.props.inputFunction(this.state.nameInput, newId) } render(){ console.log(this.props.id) return ( <div className = 'dogue-container'> <img className = 'img' src = {this.props.dogList}/> <br/> <form onSubmit = {this.handleSubmit} className = 'form'> <input onChange ={this.handleChange} className ='input' type = 'text' placeholder = 'Enter dog name' /> <br/> <button className = 'button'>Submit</button> </form> <h2 className = 'text'>Name: {this.props.name} </h2> </div> ) } } export default Dogue
Final Fixed updateStateWithInput Function in App Component
async updateStateWithInput (nameInput, id) { const newDog = { id: id, dogName: nameInput } // Update state immutably this.setState(prevState => ({ dogName: [...prevState.dogName, newDog] })) // Post only the new dog, add error handling to debug await axios.post('http://localhost:3000/dogs', newDog) .then(res => { console.log('New dog added successfully:', res.data) }) .catch(err => { console.error('Error adding dog:', err) // Critical for debugging backend issues }) }
Extra Tips
- Add the
.catchblock to your Axios call to catch network errors or backend validation issues that might be blocking the POST. - If your backend automatically generates IDs (common in databases like MongoDB or PostgreSQL), you can omit sending the
idin the POST request and use the ID returned from the backend to update your React state instead.
内容的提问来源于stack exchange,提问作者Josh Simon

