【问题标题】:how to make this axios delete request work?如何使这个 axios 删除请求起作用?
【发布时间】:2020-01-11 17:27:42
【问题描述】:

我正在使用 react、node js 和 MongoDB 创建一个银行应用程序。 数据是通过用户完成的 3 个不同输入发布的,但我在删除请求时遇到问题。它分为 3 个不同的类(相应地传递了道具)。我得到的错误是它无法读取未定义的属性_id。 id 是从数据库接收的。我怎样才能让它工作?提前致谢!

class App extends Component {
  constructor() {
    super()
    this.state = {
      transactions: []
    }
  }

  deleteTransaction = async (transaction) => {
    await axios.delete('http://localhost:8080/transaction', {data: {id: transaction._id }})
    let response = await this.getTransactions()
    this.setState({ transactions: response.data })
  }
class Transactions extends Component {
    deleteTransaction = () => { this.props.deleteTransaction() }
class Transaction extends Component {
   <button onClick={this.props.deleteTransaction.bind(this)}><DeleteIcon /></button>

【问题讨论】:

  • 我可以看看你的交易数组数据结构吗?请 console.log(transaction) 并查看数据结构。并检查事务是数组还是对象?问题是事务对象没有 _id 属性
  • @jualahmed 这是一个对象,ID 由数据库自动创建,如下所示:{ "_id": { "$oid": "5e18fccefbfecb25481c33d4" }, "amount": 21, "vendor": "as", "category": "ds", "__v": 0 }
  • 使用 this.transactions._id.$oid 获取这个 id
  • @devPom 我已经为您的问题发布了答案。

标签: node.js reactjs mongodb


【解决方案1】:

当它作为道具传递时,您不需要使用绑定。

首先,您必须删除在 Transactions 组件中声明的 deleteTransaction 函数

其次,您必须在应用组件中声明的deleteTransaction函数中传递事务参数的值

<button onClick={(event) => this.props.deleteTransaction(transaction)}><DeleteIcon/></button>

您尚未将值传递给回调函数,这就是您获得cannot read the property _id of undefined 的原因。默认情况下,deleteTransaction(App) 中的事务参数值未定义。由于您没有将任何值传递给事务参数,因此它按预期工作。

注意: 尽可能尝试使用 React Context API,这将避免道具钻孔。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-08
    • 2018-12-24
    • 2020-08-14
    • 2018-04-10
    • 1970-01-01
    • 2018-11-26
    • 2018-12-24
    • 2020-02-24
    相关资源
    最近更新 更多