【问题标题】:How to properly dispatch an axios delete with react redux如何使用 react redux 正确调度 axios 删除
【发布时间】:2022-01-24 00:30:30
【问题描述】:

我正在尝试在删除请求后刷新状态。正确的 id 正在被删除,但它根本没有刷新状态,因为操作负载是空的。以下是我当前的代码。

actions\index.js

...
function deleteCustomerSucceeded(customer){
    return{
        type:"DELETE_CUSTOMER_SUCCEEDED",
        payload:{
           customer
        }
    }
}

export function deleteCustomer(id){
    return(dispatch) =>{
        api.deleteCustomer(id).then((res) => {
            dispatch(deleteCustomerSucceeded(res.data))
        })
    }
...

reducers\index.js

...
    case 'DELETE_CUSTOMER_SUCCEEDED':{
        return{
            ...state,
            customers: state.customers.filter(customer => customer.id !== action.payload)
        }
    }
...

api\index.js

export function deleteCustomer(id){
    return client.delete(`/customers/${id}`)
}

myview.js

  deleteCustomer(){
      let state = {submitted: true}
      this.props.onDeleteCustomer(this.state.customer.id)
      state = {
        ...state,
        customer: this.emptyCustomer,
        deleteCustomerDialog: false
    }
    this.setState(state)
  }

如果需要进一步澄清或您可能需要查看任何其他代码来帮助回答此问题,请告诉我。

【问题讨论】:

  • 有效载荷可能为空,因为删除端点没有返回任何数据,因此res.data 将为空。您可以做的不是将res.data 作为参数传递给deleteCustomerSucceeded 动作创建者,而是可以传入id 参数:dispatch(deleteCustomerSucceeded(id))
  • @Kapobajza 帮助我解决了这个问题。我以为你必须从成功中获得 res.data,但现在我看到我可以使用 res 来完成它,只需将我需要的数据传递给它。换掉东西后,我得到了它的工作,非常感谢我花了太多时间来解释为什么它不起作用,现在答案似乎很明显,为什么它会空空如也。非常感谢!

标签: javascript reactjs redux axios redux-thunk


【解决方案1】:

在 Kapobajza 回答后,我对代码进行了这些更改以使其正常工作。

reducers\index.js

    case 'DELETE_CUSTOMER_SUCCEEDED':{
        return{
            ...state,
            customers: state.customers.filter(customer => customer.id !== action.payload.id)
        }
         
    }

actions\index.js

function deleteCustomerSucceeded(id){
    return{
        type:"DELETE_CUSTOMER_SUCCEEDED",
        payload:{
           id
        }
    }
}

export function deleteCustomer(id){
    return(dispatch) =>{
        api.deleteCustomer(id).then((res) => {
            dispatch(deleteCustomerSucceeded(id))
        })
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-20
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 2018-01-28
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多