繁体   English   中英

当我多次单击该按钮时,数组会获得一个值。 我希望它采用 function 中的所有值

[英]When I click the button more than once, array gets a value. I want it to take all values in the function

我有一个 listAPI 值,可以从 API 获取信息。 其output如下。

//output - console.log(listAPI)

5) [{…}, {…}, {…}, {…}, {…}]
0: {id: "1", name: "name 1", active: "true"}
1: {id: "2", name: "name 2", active: "false"}
2: {id: "3", name: "name 3", active: "false"}
3: {id: "4", name: "name 4", active: "true"}
4: {id: "5", name: "name 5", active: "true"}

当我单击 Select 按钮时,我想将此数据 map 到 firstList 的活动值和 false 到 secondList。

然后我打开一个模式并在输入部分显示 firstList 和 secondList 值。

const selectAll = () => {
        console.log(listAPI)
        listAPI.map((data) => {
            console.log(data) 
            if (data.active === false) {
                console.log(data.name)
                setFirstList([...firstList,data.id])
            }
            else {
                setSecondList([...secondList, data.id])
            }
        })
        console.log(firstList)
        console.log(secondList)
     }

代码运行时不会填充 firstList 和 secondList 值。 我怎样才能解决这个问题? 我不明白为什么它不起作用。 它只是不向列表添加值。 当我多次单击 select 按钮时,它才开始添加最后一个值。

原因在您的代码中:

if (data.active === false)

您将data.active stringfalse进行比较,后者是boolean

State 更新不同步。 尝试使用这个:

listAPI.forEach((data) => {
   if (data.active === "false") {
       setFirstList((prevFirstList) => [...prevFirstList, data.id]);
    else {
        setSecondList((prevSecondList) => [...prevSecondList, data.id]);
    }
});

编辑:根据https://stackoverflow.com/a/67126603/2333214更新比较

长版:

listAPI.forEach((data) => {
      if (data.active === "false") {
        setFirstList((prevFirstList) => {
          const newFirstList = [...prevFirstList, data.id];
          console.log(newFirstList);
          return newFirstList;
        });
        else {
          setSecondList((prevSecondList) => {
            const newSecondList = [...prevSecondList, data.id];
            console.log(newSecondList);
            return newSecondList;
          });
        }
      });

您可以使用减速器 ZC1C425268E683894B666Z 和 map 检查每个 object 和 map 的activate state 的结果。

const key = isActive === 'true' ? 'active' : 'inactive'

 const listApi = [ { id: "1", name: "name 1", active: "true" }, { id: "2", name: "name 2", active: "false" }, { id: "3", name: "name 3", active: "false" }, { id: "4", name: "name 4", active: "true" }, { id: "5", name: "name 5", active: "true" }, ]; const result = listApi.reduce((acc, { active: isActive, ...rest }) => ((key => ({...acc, [key]: [...acc[key], {...rest }] })) (isActive === 'true'? 'active': 'inactive')), { active: [], inactive: [] }); console.log(result);
 .as-console-wrapper { top: 0; max-height: 100%;important; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM