开发者问题收集

删除按钮-onDelete函数

2020-05-21
776

我的删除按钮以前可以工作,但现在当我为每个挑战添加喜欢/不喜欢满意度部分时,它就停止工作了。有人能帮我找出这个错误吗?这是我按下按钮时在终端中收到的消息:DELETE /allchallenges/[object%20Object] 200 1.623 ms - 214----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


import React from 'react'
import DefaultLayout from "../layout/Default"
import Challengebox from '../components/Challengebox'
import axios from "axios";
import "./Allchallenges.css"
import { faThumbsUp } from "@fortawesome/free-solid-svg-icons";
import { faThumbsDown } from "@fortawesome/free-solid-svg-icons";
import { faBalanceScale } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

class Allchallenges extends React.Component {
    constructor() {
        super()

        this.state = {
           challenges: []
        }

        this.onDelete=this.onDelete.bind(this)
        this.sortByTitle=this.sortByTitle.bind(this)
        this.sortByDescription=this.sortByDescription.bind(this)
        this.searchChallenges=this.searchChallenges.bind(this)
        this.challengestotal=this.challengestotal.bind(this)
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: `${process.env.REACT_APP_API_BASE}/allchallenges`,
            withCredentials: true
        })
        .then(response => {
            console.log(response)
            let challengeslist = response.data;
            this.setState({challenges: challengeslist})
        })
        .catch(error => {
            console.log("You've made an error charles: ",error)
        })
    }

    onDelete(challengeId){
        axios
        .delete(`${process.env.REACT_APP_API_BASE}/allchallenges/${challengeId}`)
        .then(response => {
            const challenges = this.state.challenges.filter(challenge => challenge._id !== challengeId)
            this.setState({challenges})
        })
        .catch(err => console.log(err))
    }

    sortByTitle() {
        let challengesSortTitle = this.state.challenges.sort((a,b) => {
            return a.title > b.title ? 1 : -1
        })
        this.setState({
            challenges:challengesSortTitle
        })
    }

    sortByDescription() {
        let challengesSortDescription = this.state.challenges.sort((a,b) => {
            return a.description > b.description ? 1 : -1
        })
        this.setState({
            challenges:challengesSortDescription
        })
    }

    searchChallenges(e){ // eslint-disable-next-line
        let challengesSearch = this.state.challenges.filter(challenge => { 
            if(challenge.title){
                if(challenge.title.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true 
                }   
            }
        })
        this.setState({
            challenges:challengesSearch
        })
    }

    challengestotal(){
        return `${this.state.challenges.length}`
    }

    // handleLikeDislike(e){
    //     e.preventDefault()
    // }

    render(){
        return (
            <DefaultLayout>
                <div className="challengeoverviewlist">
                    <h1>All challenges</h1>   

                    <div className="headers">
                        <button onClick={this.sortByTitle} className="sorttitle">
                            Sort based on TITLE
                        </button>

                        <button onClick={this.sortByDescription} className="sortdescription">
                            Sort based on DESCRIPTION
                        </button>

                        <button onClick={this.sortByDescription} className="sortdescription">
                            Sort based on DAREDEVILS
                        </button>

                        <input className="searchbox" type="text" placeholder="Search for a challenge title here..." onChange={this.searchChallenges} />

                        <p className="challengescounterbox">{this.challengestotal()} challenges</p>
                    </div>

                    <div className="challengeboxes">
                        {    
                        this.state.challenges.map(challenge => 
                            (
                                <div className="totalbox" key={challenge._id}>

                                    <div className="likedislikesbox">
                                        <div className="likecontainer">
                                            <div className="leftalignment"><FontAwesomeIcon icon={faThumbsUp} /></div>
                                            {/* onClick={(e)=> this.handleLikeDislike(e)} */}
                                                <p className="likestat">Likes{challenge.likes}</p>
                                        </div>

                                        <div className="dislikecontainer">
                                            <div className="leftalignment"><FontAwesomeIcon icon={faThumbsDown}/></div>
                                            <p className="dislikestat">Dislike</p>
                                        </div>

                                        <div className="satisfactioncontainer">
                                            <div className="leftalignment"><FontAwesomeIcon icon={faBalanceScale}/></div>
                                            <p className="satisfactionstat">Satisf %</p>
                                        </div>
                                    </div>

                                    <Challengebox 
                                        key={challenge._id} 
                                        id={challenge._id} 
                                        title={challenge.title} 
                                        description={challenge.description}
                                    />

                                    <button className="deletebutton" onClick={this.onDelete}>
                                        Delete
                                    </button>

                                </div>
                            ))                                                                      
                        }
                    </div>

                </div>    
            </DefaultLayout>
        )
    }
}

export default Allchallenges
2个回答

看起来您忘记将挑战 ID 传递给处理程序。

 <button className="deletebutton" onClick={() => this.onDelete(challenge._id)}>
                                        Delete
                                    </button>
Michal Szorád
2020-05-21

onClick 接受事件对象作为其参数。您已假设它将是要删除的挑战的 ID,因此您尝试将其添加到查询字符串中。这就是您收到对象错误的原因。

相反,将 onClick 传递给匿名函数并使用 ID 调用 onDelete

<button className="deletebutton" onClick={() => this.onDelete(challenge._id)}>

由于您不需要该事件,我们不将其包含在函数中,而是使用当前映射元素的 ID 调用 onDelete

Brian Thompson
2020-05-21