如何在map方法中只显示匹配id的信息

how to only display the information with matched id inside map method

我发现自己很愚蠢,无法理解逻辑。

我想显示一些由 onClick 触发的信息,并且只显示匹配 id 的信息。 例如,如果我单击带有 id1 的按钮,它只想显示带有 id:1 的特定对象中的值,例如 descriptionlibrary, 等等。 现在,所有数据都显示出来了,因为我在 material ui 中使用组件,所以每个抽屉组件都显示在彼此之上(重叠)。 我知道造成这种情况的原因是因为我在 map 方法中有抽屉组件,但有什么可能的解决方案?

下面是我的简单代码, 我的数据结构如下所示,

export const projectdata = [
    {
        id: 1,
        title: "",
        subtitle: "",
        thumbnail: "",
        description:
            "",
        tech: [
        ],
        library: [""],
        WebsiteUrl: "",
        GitHubUrl: "",
    },
    ...more data with sequential id number...
]

原文:

    const handleDrawerOpen = (event) => () => {
        setOpen(!open);
    };
...
...
         <SwipeableDrawer
                 open={open}
                 onClose={handleDrawerOpen(false)}
                 onOpen={handleDrawerOpen(true)}>
               ***...only show data with matched id...***
         </SwipeableDrawer>

我已经映射数组在网页上显示数据 div 像这样,

<div>
 { projectdata?.map(({ id, title, subtitle, thumbnail, description, tech, WebsiteUrl, GitHubUrl, library, index }) => (
      <>
         <Card>
          ...some info displayed here...

               <button onClick={handleDrawerOpen(id)}></button>
         </Card>
         <SwipeableDrawer>
               ***...only show data with matched id...***
         </SwipeableDrawer>
      </>
))}
<div>

我能想到的一个方案:

with useState(), 传入 id 作为 prop

const [projectDetailId, setProjectDetailId] = useState(null);
const [projectDetailPage, setProjectDetailPage] = useState(false);

const handleDrawerOpen = (id) => {
     setProjectDetailId(id);
     setProjectDetailPage(true);
};
const handleDrawerClose = () => {
        setProjectDetailId(null);
        setProjectDetailPage(false);
};
...
...
{projectDetailId === id ? 
         <SwipeableDrawer
              open={projectDetailPage}
              onClose={handleDrawerClose}
         ></SwipeableDrawer>
         : null
}

但是,这会触发抽屉的奇怪行为(滞后且没有动画),尤其是在移动设备上。 可能是由于这种逻辑 projectDetailId === id ? true : false.

好的,更新后,您的问题是您创建了多个抽屉,每个抽屉一个。当你点击打开并将 open 属性设置为 true 时,你所有的抽屉都使用相同的属性,所以它们都会打开。

您应该将抽屉从 for 中移出,只创建一个,然后将具有 id 的对象作为 prop 发送到您拥有的抽屉的内容中。

类似于:

 const handleDrawerOpen = (yourData) => () => {
    setOpen(!open);
    setYourData(yourData)
 };
 
 ...

 // and somewhere on your code
 <SwipeableDrawer open={open}>
          
   <SomeComponentToShowTheData data={yourData}/>

 </SwipeableDrawer>