reactjs 如何更新对象数组react的孙值

vlurs2pr  于 2023-03-17  发布在  React
关注(0)|答案(1)|浏览(127)

从数据库中检索数据后,当用户单击按钮时,我正要更新字段的值,在这种情况下,我需要更新flag_used的值。

// App.ts

interface UserSponsorType {
  id: number,
  value: string,
  flag_used?: boolean
}

interface SponsorType{
  user_sponsors: Array<UserSponsorType>
  id: number
}

export function App() {
   const selected<Array<SponsorType>> = data; // from the database

   const onHandlerClick = () => {
     selected.user_sponsors.map(userSponsor => {
        // update the value of flag_used here
        // Note that flag_used is optional
     });
     console.log(selected);
   }

   return <Button onClick={onHandlerClick}>Click</Button>
}

如果flag_used不等于true,如何更新第一个/最近对象的flag_used值?
示例数据:

data = [
   {
     id: 1,
     user_sponsors: [
        { id: 1, value: "test", flag_used: false},
        { id: 2, value: "test"},
     ]
   },
   {
     id: 2,
     user_sponsors: [
        { id: 3, value: "test", flag_used: true},
        { id: 4, value: "test", flag_used: false},
     ]
   },
   {
     id: 3,
     user_sponsors: [
        { id: 5, value: "test", flag_used: true},
        { id: 6, value: "test", flag_used: true},
        { id: 7, value: "test", flag_used: false},
        { id: 8, value: "test", flag_used: false},
        { id: 9, value: "test", flag_used: false},
     ]
   }
]
whlutmcx

whlutmcx1#

你可以试试这个

const onHandlerClick = () => {
    let flagFirstItem = true;
    const newSelected = selected.user_sponsors.map(userSponsor => {
        if (userSponsor.flag_used === false && flagFirstItem) {
            flagFirstItem = false;
            return {
                ...userSponsor,
                flag_used: true,
            }
        }
        return userSponsor
    });
    console.log(newSelected);
}

相关问题