axios 我尝试执行删除请求,但遇到此错误

9w11ddsr  于 2022-12-12  发布在  iOS
关注(0)|答案(1)|浏览(296)

Front End

import React,{useState, useEffect} from 'react'
import axios from 'axios'

function Renderreview() {
const [renderReview, setRenderReview] = useState([])

useEffect(()=>{
    axios.get('/reviews')
    .then(res => {
    console.log(res)
    setRenderReview(res.data)
    })
    .catch(err => {
    console.log(err)
    })
},[])

function handleDelete (id){
    console.log(renderReview.id)

    axios.delete(`/reviews/${renderReview.id}`,)
}

return (
    <div className='card1'>
    <h2>reviews</h2>
    {renderReview.map((renderReview) => {
        return(
        <div className='renderedreviews'>{renderReview.review} 
        
        <button onClick={handleDelete} key={renderReview.review}>Delete</button>
        </div>
        )
    })}
    </div>
)
}

export default Renderreview

Back End

def destroy
review =Review.find_by(id: params[:id])
if review.destroy
    head :no_content
else
    render json: {error: review.errors.messages}, status: 422
end
end

This is the error displaying on my console
DELETE http://localhost:4000/reviews/undefined 500 (Internal Server Error)
Uncaught (in promise)
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}

zzlelutf

zzlelutf1#

请尝试以下操作,您使用的ID不正确:

import React, { useState, useEffect } from 'react'
import axios from 'axios'

function Renderreview() {
    const [renderReview, setRenderReview] = useState([])

    useEffect(() => {
        axios.get('/reviews')
            .then(res => {
                console.log(res)
                setRenderReview(res.data)
            })
            .catch(err => {
                console.log(err)
            })
    }, [])

    function handleDelete(id) {
        axios.delete(`/reviews/${id}`,)
    }

    return (
        <div className='card1'>
            <h2>reviews</h2>
            {renderReview.map((renderReview) => {
                return (
                    <div className='renderedreviews'>{renderReview.review}
                        <button
                            onClick={() => {
                                handleDelete(renderReview.id);
                            }}
                            key={renderReview.review}>
                            Delete
                        </button>
                    </div>
                )
            })}
        </div>
    )
}

export default Renderreview

相关问题