javascript - 如何在数组中制作删除按钮
问题描述
我正在尝试在聊天数组中添加一个删除按钮。因此,当单击该按钮时,它会删除特定的聊天。但是,一旦组件加载,所有聊天都会被删除,因为聊天在地图功能中。 谁能帮我解决这个问题?
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;
解决方案
您onClick
错误地使用了事件。
<IconButton>
<HighlightOffIcon onClick={removeMatches(Id,match._id)}/>
</IconButton>
正确的方法:
<IconButton>
<HighlightOffIcon onClick={() => removeMatches(Id,match._id)}/>
</IconButton>
您希望removeMatches
稍后调用您的函数。在您的情况下,一旦组件呈现,该removeMatches
函数就会被调用,甚至无需等待点击事件。
将回调函数传递给onClick
确保只有当点击发生时才运行removeMatches
函数,然后根据您的逻辑清除相应的项目。
推荐阅读
- css - 有没有办法将 Bootstrap 类属性写入 CSS 文件,或者有没有办法让它工作?
- powershell - 无法将参数传递给 ConvertTo-SecureString,只有脚本定义的变量
- perl - Perl Tcl::pTk 读取 Tcl 版本
- java - 执行方法时如何写入和保存日志文件(通过应用程序属性设置级别)
- javascript - 使用 HTML5 和 javascript 从 iPhone Chrome 录音
- initialization - 在 Cobol 中初始化可变长度
- javascript - 在 DOM 中加载后,我可以取消注释 JavaScript 函数中的注释代码行吗?
- apache - Websphere 应用程序问题中的 IHS 与 Apache
- typescript - typescript error TS2531 Object is possibly 'null' is NOT being suppressed by strictNullChecks : false
- c# - 如何在不知道 C# 中的基础类型的情况下遍历数组