Javascript 如何从react js中的map方法中仅访问一项

Javascript 如何从react js中的map方法中仅访问一项,javascript,node.js,reactjs,Javascript,Node.js,Reactjs,我的问题可能不清楚,但这是我的问题。这是我的卡片,我使用map方法从数组中获得,并显示每张卡片上的每个项目。 我已经触发了“编辑”按钮,这样它就会显示隐藏的文本(只想在一张卡片上看到)。但当我只点击一张卡片时,所有卡片都会显示隐藏的信息。你能帮帮我吗 我想在点击编辑按钮的卡片上看到“只想在一张卡片上看到这个”文本 <Button size="small" onClick={() => setEditIndex(editIndex => edit

我的问题可能不清楚,但这是我的问题。这是我的卡片,我使用map方法从数组中获得,并显示每张卡片上的每个项目。 我已经触发了“编辑”按钮,这样它就会显示隐藏的文本(只想在一张卡片上看到)。但当我只点击一张卡片时,所有卡片都会显示隐藏的信息。你能帮帮我吗

我想在点击编辑按钮的卡片上看到“只想在一张卡片上看到这个”文本

 <Button
   size="small"
   onClick={() => setEditIndex(editIndex => editIndex === index ? null : index)}
 >
   Edit
 </Button>
这是我的密码:

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>
const[edit,setedit]=useState(false)
{allitems.map((一项,索引)=>{
返回(
{oneitem.title}
/

{oneitem.description}

创建于:{oneitem.createdAt}

已删除(oneitem.\u id)}>删除 setedit(!edit)}>编辑问题 您正在使用单个布尔
edit
状态值来触发所有映射元素的编辑模式

解决方案 使用一些可以与数据关联的
edit
状态,例如索引或项
id
属性。由于我没有看到使用的任何GUI,我将演示索引

  • 使用元素索引来标识处于“编辑”模式的内容,null表示没有任何内容处于“编辑”模式

  • 更新“切换”按钮以切换新索引,如果单击了相同的按钮,则更新为空

     <Button
       size="small"
       onClick={() => setEditIndex(editIndex => editIndex === index ? null : index)}
     >
       Edit
     </Button>
    
  • 附加说明 我看到你有一个删除按钮:

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

    如果要从基础数据中删除元素,则不希望使用数组索引作为React键。相反,应使用每个元素的唯一标识属性,如
    \u id
    (它们只需要在同级之间唯一)。因此,不要使用索引设置“编辑”当你在地图中使用一个常用的编辑值时,如果你把“编辑”的主值改为“true”(在这种情况下),它会认为所有的卡都是真的。 不,这里是您可以尝试做的(我认为您一次只能编辑一张卡),而不是将编辑保持为布尔值(true | false),使用它作为整数值在数组中存储卡的索引

    步骤:

  • 默认情况下,keep edit=null
  • setEdit函数可以变成这样:(考虑基于类的状态)
  • setEdit(editVal)=>{
    if(this.state.edit==editVal){
    这是我的国家({
    编辑:空
    })
    }
    否则{
    这是我的国家({
    编辑:editVal
    }
    }
    
    }
    @Rupak欢迎。如果这个答案和解释有帮助,那么如果可以,我邀请你也投上一票。干杯,祝你好运!@drewerese,我觉得,在这个问题上,你会是帮助我的合适人选,请你研究一下这个问题,因为我完全被工作困住了。。
    <Button size="small" onClick={()=> deleted(oneitem._id)} >Delete</Button>