Javascript 带挂钩的物料折叠台

Javascript 带挂钩的物料折叠台,javascript,reactjs,material-ui,Javascript,Reactjs,Material Ui,我一直在试图解决这个问题,但运气不好,我需要我的handleClick()函数的帮助,它可以同时折叠和展开所有表行,如图所示。你知道为什么会这样吗?如何修复它 2-组件安装时也会多次点火 从“React”导入React,{useffect,useState}; 进口{ 盒子, 崩溃 IconButton, 桌子 表体, TableCell, 桌上容器, 桌面, TableRow, 排版, 纸张 }来自“@材料界面/核心”; 从“@material ui/icons/KeyboardArrowD

我一直在试图解决这个问题,但运气不好,我需要我的handleClick()函数的帮助,它可以同时折叠和展开所有表行,如图所示。你知道为什么会这样吗?如何修复它

2-组件安装时也会多次点火


从“React”导入React,{useffect,useState};
进口{
盒子,
崩溃
IconButton,
桌子
表体,
TableCell,
桌上容器,
桌面,
TableRow,
排版,
纸张
}来自“@材料界面/核心”;
从“@material ui/icons/KeyboardArrowDown”导入键盘箭头向下图标;
从“@material ui/icons/KeyboardArrowUp”导入键盘箭头图标;
从“uuid”导入{v4 as uuid};
函数可折叠表(){
常量[fetchedData,setFetchedData]=useState([]);
const[isLoding,setIsLoding]=useState(false);
const[expanded,setExpanded]=useState();
const getData=async()=>{
const response=等待获取(“https://reqres.in/api/users?page=2");
const result=wait response.json();
setIsLoding(假);
setFetchedData(
result.data.map((用户)=>({
用户数据:{
id:user.id,
firstName:user.first_name,
lastName:user.last_name,
电子邮件:user.email
},
其他数据:{
化身:user.avatar
}
}))
);
};
常量handleClick=()=>{
setExpanded(!expanded);
};
useffect(()=>{
getData();
}, []);
返回(
指数
身份证件
名字
姓
电子邮件
{isLoding
“装载…”
:fetchedData.map((用户,索引)=>(
{扩展(
) : (
)}
{index}
{user.user_data.id}
{user.user_data.firstName}
{user.user_data.lastName}
{user.user_data.email}
Txns历史
阿凡达
阿凡达
))}
);
}
导出默认可折叠表;
我试着通过它的索引值来切换每一个,就像这样


常量handleClick=(索引)=>{
集膨胀({
…扩大,
[索引]:!已扩展[索引]
});
}
//...

但仍然无法按预期工作…

这是因为您的
展开状态是所有
折叠组件的状态

这是映射后组件树的当前外观:

<>
  <Collapse
    in={expanded}
  />
  <Collapse
    in={expanded}
  />
  <Collapse
    in={expanded}
  />
</>

const getData = async () => {
  ...
  // after you receive your data, initialize all expanded boolean to be false so they are all closed by default
  setExpanded([...Array(result.data.length)].map((val) => false));
}; 

<Collapse
  in={expanded[index]} // we use index to reference the correlated expanded state value
  timeout="auto"
  unmountOnExit={true}
>

<IconButton
  aria-label="expand row"
  size="small"
  onClick={() => handleClick(index)} // onClick pass the index clicked
>

// set new state depending on what Collapse index was clicked
const handleClick = (index) => {
  setExpanded(
    expanded.map((boolean_value, i) => {
      if (index === i) {
        // once we retrieve the collapse index, we negate it
        return !boolean_value;
      } else {
        // all other collapse will be closed
        return false;
      }
    })
  );
};