首页 > 解决方案 > 如何在数组中制作删除按钮

问题描述

我正在尝试在聊天数组中添加一个删除按钮。因此,当单击该按钮时,它会删除特定的聊天。但是,一旦组件加载,所有聊天都会被删除,因为聊天在地图功能中。 谁能帮我解决这个问题?

import React,{useState,useEffect} from 'react'
import Chat from './Chat';
import {axiosInstance} from '../axios';
import { IconButton} from '@material-ui/core';
import HighlightOffIcon from '@material-ui/icons/HighlightOff';
function Chats(props) {

    const [matches,setMatches] = useState([]);
    const [Id, setId] = useState('');  

    useEffect(() => {
        console.log('Id : ',props.id);
        setId(props.id);
        async function fetchMatches(Id){
            console.log('FETCH MATCHES');
            axiosInstance.get(`/matchlist/${Id}`)
            .then((req) =>{
                setMatches(req.data[0].matches)
            })
            .catch((err) => console.log(err));
        }
        fetchMatches(props.id);
    }, []);


    const removeMatches = (userId,matchId) =>{
           console.log(userId,'  ',matchId);
             axiosInstance.delete(`/matchlist/${userId}/${matchId}`)
             .then((matches) => console.log('matches',matches.data))
             .catch(err => console.log(err));
    }

    return (
        <div className='chats'>
            {
                matches.map((match) =>{
                    return  <div className='chat'>
                                <Chat 
                                    name={match.firstname +' '+match.lastname}
                                    message='message'
                                    timestamp="time taken"
                                    profilePic = {match.imgUrl}
                                    id={match._id}
                                />
                                <IconButton>
                                    <HighlightOffIcon  onClick={removeMatches(Id,match._id)}/>
                                </IconButton>
                            </div>
                })
            }
        </div>
    )
}

export default Chats;

标签: javascriptreactjsmongodbchatreact-fullstack

解决方案


onClick错误地使用了事件。

 <IconButton>
      <HighlightOffIcon onClick={removeMatches(Id,match._id)}/>
 </IconButton>

正确的方法:

 <IconButton>
      <HighlightOffIcon onClick={() => removeMatches(Id,match._id)}/>
 </IconButton>

您希望removeMatches稍后调用您的函数。在您的情况下,一旦组件呈现,该removeMatches函数就会被调用,甚至无需等待点击事件。

将回调函数传递给onClick确保只有当点击发生时才运行removeMatches函数,然后根据您的逻辑清除相应的项目。


推荐阅读