You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 .catch block 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 id in the POST request and use the ID returned from the backend to update your React state instead.

内容的提问来源于stack exchange,提问作者Josh Simon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:43:11