放入请求获取ID | Axios,React,Redux

时间:2017-08-06 23:25:44

标签: javascript reactjs redux put axios

我想向我的服务器发出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我可以看到我在输入字段中输入的所有的东西(我要改变的东西),但我也得到了这个: enter image description here

有时404。所以我的问题是如何获得id以便我可以发出此请求。谢谢。

这是我致电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
)

2 个答案:

答案 0 :(得分:0)

您目前正在做的是将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才能获得正确的updateSettings ID。

另外请注意,如果您以这种方式调度异步操作,那么根据您使用的中间件,您可能必须在异步数据进入时调用dispatch(例如,您可以访问{{ 1}})。

答案 1 :(得分:0)

您错过了updateSettings()功能

上的ID

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

然后是您调用它的行:

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

你的物品在这里是你的身份,而物品无处可寻,我认为这是你现在至少可以解决大部分问题的地方。

相关问题