reactjs - 如何从页面中删除数据并且它不显示?
问题描述
当我删除它时,我试图在我的组件中显示新数据,所以我想要做的是,当我删除该数据时,它将不再显示在页面上,但是当我单击按钮时,我有一个错误“购物车。地图不是函数”,我需要您的帮助来告诉我如何在我的页面中显示新数据并修复错误。
useEffect(() => {
axios.get(url)
.then(response=>{
setCart(
response.data
);
})
.catch(e =>{
console.log(e);
})
}, [url])
const handleDeleteItems = async(key, cart_id) =>{
var yes = confirm("You are going to remove an item from your cart, are you sure you want to delete item?")
if(yes===true){
alert("succefull");
const temp = [...cart];
temp.splice(cart_id, 1);
setCart({
cart:temp
});
}}
这是我的表格,我在其中显示数据,但是当我单击按钮时它给了我一个错误
return (
<div>
<Table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{cart.map((cart, key)=>{
return(
<tr key={cart.id}>
<td>{cart.name}</td>
<td>{cart.price}</td>
<td>
<Button onClick={() => handleDeleteItems(key, cart.id)} variant="danger">Delete</Button>
</td>
</tr>
)})}
</tbody>
</Table>
</div>
解决方案
首先,如果购物车数据为空或未初始化,您应该添加一个验证以不尝试加载购物车数据。在此示例中,如果购物车为空,我们将显示“尚无产品”。
{cart ? cart.map((cart, key)=>{
return(
<tr key={cart.id}>
<td>{cart.name}</td>
<td>{cart.price}</td>
<td>
<Button onClick={() => handleDeleteItems(key, cart.id)} variant="danger">Delete</Button>
</td>
</tr>
)}) : <> <td>No products yet.</td>
</>}
推荐阅读
- javascript - Webpack 多重配置失败
- bluetooth - Xbox One S 无线控制器可能无效的 HID 描述符
- android - 有没有办法禁止键盘移动LinearLayout?
- neo4j - 在关系边上过滤查询 N 跳的路径
- java - 休眠异常,“意外的 AST 节点”
- bash - 尝试运行脚本时在我的苹果终端中获取代码:'UNABLE_TO_VERIFY_LEAF_SIGNATURE'}'Uncaught Exception throw'
- javascript - 有没有办法在 pwa 中安排离线通知?
- influxdb - 在 InfluxDB 中存储统计数据
- java - Spring security:如果用户不满足特定条件,则使每个页面重定向
- tabulator - 制表器 - 甚至无法通过快速入门开始