[英]Put request get ID | Axios, React, Redux
我想向服務器發出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,以便發出此放置請求。 謝謝。
這是我稱之為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
)
您當前正在做的是將onSubmit
處理函數接收到的事件對象傳遞給updateSettings
方法。
請注意,在事件處理程序中,您可以訪問state
和props
:
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.id
或item.id
以獲得正確的updateSettings
需求。
還請注意,如果您以這種方式分派異步操作,則取決於所使用的中間件,您可能必須在res.data
異步數據時(例如,可以訪問res.data
)調用dispatch
。
您錯過了updateSettings()
函數上的ID
看這行: export const updateSettings = function(id, item) {};
然后是您稱之為的行:
submit(values) {
this.props.updateSettings(values)
}
您的項目是您的ID,在哪里都找不到,我認為這是您現在至少可以解決大部分問題的地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.