【问题标题】:Put request get ID | Axios, React, ReduxPut请求获取ID | Axios、React、Redux
【发布时间】:2025-12-29 01:30:11
【问题描述】:

我想向我的服务器发出 PUT 请求,但为了做到这一点,我需要一个我需要更新的特定对象的标识符。这就是我的问题,我不知道如何获取组件 ID,因此我可以满足我的 PUT 请求。这是目前的代码:

import axios from 'axios'
import settings from '../../../../settings'

axios.defaults.baseURL = settings.hostname

export const updateSettings = function(id, item) {
  return dispatch => {
    axios
      .put(`${settings.hostname}/locks/${id}`, item)
      .then(res => res.data)
      .catch(err => console.log(err))
  }
}

当 console.log item 我可以看到我在输入字段中输入的所有 内容(我想要更改的内容),但我也得到了这个:

有时404。所以我的问题是如何获取 id 以便我可以提出这个 put 请求。谢谢。

这是我打电话给updateSettings的地方:

import React, { Component } from 'react'
import { updateSettings } from './redux/actions/updateSettingsAction'
import DoorSettingsForm from './components/doorsSettingsForm'
import { connect } from 'react-redux'

class DoorSettingsContainer extends Component {
  submit(values) {
    this.props.updateSettings(values)
  }

  render() {
    return (
      <div>
        <DoorSettingsForm
          onSubmit={this.submit.bind(this)}
          item={this.props.location.state.item}
        />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return { data: state.data }
}

export default connect(mapStateToProps, { updateSettings })(
  DoorSettingsContainer
)

【问题讨论】:

  • 你怎么称呼updateSettings?看起来您正在传递一个对象,而不仅仅是一个原语。
  • 我已经添加了一些代码。
  • 值对象是什么样的?

标签: javascript reactjs redux put axios


【解决方案1】:

您错过了 updateSettings() 函数上的 id

看看这一行:export const updateSettings = function(id, item) {};

然后是你调用它的那一行:

submit(values) {
    this.props.updateSettings(values)
}

您的项目是您的 id,但该项目无处可寻,我认为这是您至少目前解决大部分问题的地方。

【讨论】:

    【解决方案2】:

    您当前正在做的是将onSubmit 处理程序接收到的事件对象传递给updateSettings 方法。

    请注意,在您的事件处理程序中,您可以同时访问 stateprops

    submit() {
      // this comes from the redux binding
      const { data } = this.props
      // this is local state, not sure what else of interest is in there
      const item = this.state.location.item
    
      // Just a guess, inspect your data to see what's appropriate here.
      this.props.updateSettings(data.id, item)
    }
    

    检查您的数据,您可能需要访问data.iditem.id 以获得正确的id updateSettings 需要。

    还要注意,如果您以这种方式调度异步操作,那么根据您使用的中间件,您可能必须在异步数据进入时调用dispatch(例如,您可以在哪里访问res.data) .

    【讨论】: