如何在React JS中从map方法中获取一个特定项的访问权限?

5
我的问题可能不太清楚,但这是我的问题。我使用map方法从数组中获取卡片,并在每个卡片上显示每个项目。我已经触发了“编辑”按钮,以便它会显示隐藏的文本(只想在一个卡片中看到此内容)。但是当我点击一个卡片时,所有卡片都会显示该隐藏消息。你能帮帮我吗?
我想在单击编辑按钮的卡片中看到“只想在一个卡片中看到此内容”文本。
这是我的代码:
const [edit, setedit]= useState(false)  

<Grid container spacing={5} className="main-grid" >
{allitems.map((oneitem, index) => {
return (
<Grid item key={index} md={3} className="itemGrid" >
<Card className="card">
<CardContent>
<Typography className="" color="textSecondary" gutterBottom>
{oneitem.title}
</Typography>/
<p variant="h5" component="h2" className="description">
{oneitem.description}
</p>
<p className="" color="textSecondary">
Created At: {oneitem.createdAt}
</p>
<Button size="small" onClick={()=> deleted(oneitem._id)} >Delete</Button>
<Button size="small" onClick={()=>setedit(!edit)} >Edit</Button>  <-here is the problem
{edit && <h1>Want to see this in only one card</h1>}   
</CardContent>

这里是图片

2个回答

6

问题

您正在使用单个布尔型edit状态值来触发所有映射元素的编辑模式。

解决方案

使用一些与您的数据相关的edit状态,例如索引或项目id属性。由于我没有看到任何使用GUID,因此我将演示如何使用索引。

  1. Use the element index to identify what is in "edit" mode, null means nothing has the "edit" mode.

     const [editIndex, setEditIndex]= useState(null);
    
  2. Update the toggle button to toggle a new index or back to null if the same button is clicked

     <Button
       size="small"
       onClick={() => setEditIndex(editIndex => editIndex === index ? null : index)}
     >
       Edit
     </Button>
    
  3. Match the saved editIndex state to the currently mapped element to conditionally render the messaging.

     {editIndex === index && <h1>Want to see this in only one card</h1>}
    

补充说明

我看到你有一个删除按钮:

<Button size="small" onClick={()=> deleted(oneitem._id)} >Delete</Button>

如果您正在从基础数据中删除元素,则不应将数组索引用作React键。相反,您应该使用每个元素的唯一标识属性(如_id)作为键(它们只需要在同级元素中是唯一的)。因此,您应该使用_id而不是索引来设置“编辑”模式。

1
这个问题出现在您使用整个地图中的常见编辑值上。因此,如果您将“edit”的主要值更改为“true”(如本例),则它将认为所有卡片的编辑都是true。
不,以下是您可以尝试做的事情(我假设您每次只能编辑一张卡片),而不是将编辑保留为布尔值(true|false),请将其用作整数值以存储数组中卡片的索引。
步骤:
1. 默认情况下将edit = null
2. setEdit函数可以变成这样:(考虑基于类的状态)

setEdit(editVal) => {
  if(this.state.edit === editVal){
    this.setState({
      edit: null
      })
  }
  else{
    this.setState({
      edit: editVal
    }
  }
}

  1. 调用setEdit方法时,请使用以下方式:

onClick={()=> setEdit(index)}

  1. 现在,每次单击编辑按钮时,编辑值都会更改为新的索引值或null。

  2. 最后一步更改是将此内容替换为:

{edit && <h1>Want to see this in only one card</h1>}

替换为

{edit===index && <h1>Want to see this in only one card</h1>}

总结:

我们首先将编辑值移动到整数或null。然后点击编辑时,数组中元素的索引值被分配给“edit”。一旦发生这种情况,我们将检查编辑值是否等于索引值(步骤5),如果是,则仅为该卡显示消息。再次单击编辑后,“edit”的值将变为null(如果单击了相同的卡)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接