如何正确更改数组中对象的布尔值?

How to properly change the boolean inside of object in array?

因此,我正在尝试根据数组对象中每个电子邮件数据的 isBadData 切换图标。但我似乎无法找出如何将它保存回状态,以便它可以更新 LeadProfileComponent 中的图标图像。

这是它的样子:

checkIcon = isBadData: false
crossIcon = isBadData: true

这是我的代码:

 // ModalComponent.js
 const [leadProfile, setLeadProfile] = useState([
  {
    id: 'd114877b-074b-4aa2-a3f0-3b9446885336',
    firstName: 'wqe',
    lastName: 'wqe',
    name: 'wqe wqe',
    email: [
      {
        type: 'personal',
        address: 'qwe@hotmail.com',
        valid_since: '2010-05-09',
        isBadData: true,
      },
      {
        type: 'personal',
        address: 'wqe@hotmail.com',
        valid_since: '2017-03-09',
        isBadData: true,
      },
      {
        type: 'personal',
        address: 'wqe@aol.com',
        valid_since: '2009-01-12',
        isBadData: true,
      },
    ],
  },
]);

<LeadProfileComponent leadProfile={leadProfile} setLeadProfile={setLeadProfile} />


// LeadProfileComponent.js
const LeadProfileComponent = (props) => {
  const handleChildEmail = (email, index) => {
    props.setLeadProfile((prev: any) => {
      const value = { ...prev[0].email[index] };
      console.log('inside value');
      console.log(value);
      value.isBadData = !value.isBadData;

      console.log(value);
      // return prev;
      return [value];
    });
    console.log('props.leadProfile');
    console.log(props.leadProfile);
  };
  return (
    <>
      {
        props.leadProfile.map((lead, index) => (
          return(
      <>
        {lead.email.map(() => {

          return (
            <button
              id="btnCheck"
              onClick={() => {
                handleChildEmail(email, index);
              }}
            >
              <img
                src={
                  email.isBadData !== true
                    ? checkIcon
                    : closeIcon
                }
              />
            </button>
          )
        })}
      </>
      )
    }
    </>
  );
}

这是当您在 handChildEmail 函数中进行控制台登录时的样子:

如您所见,我能够更改电子邮件[0]的内部布尔值,但我无法将其保存回 leadProfile 状态,因为我在解构部分缺少了一部分

将您的组件分解成更小的部分,并单独管理每封电子邮件

  • LeadProfileEmailComponent.js
const LeadProfileEmailComponent = ({ initialEmailData, ...props }) => {

    const [emailData, setEmailData] = useState(initialEmailData);
   
    return (
        <button
            id="btnCheck"
            onClick={() => {
                setEmailData({
                    ...emailData,
                    isBadData: !emailData.isBadData
                });
            }}
        >
            <img
                src={
                    emailData.isBadData !== true
                        ? checkIcon
                        : closeIcon
                }
             />
        </button>
    )
}

在 LeadProfileComponent 中更改:

{lead.email.map((email) => {
    return (
        <LeadProfileEmailComponent initialEmailData={email} />
    )
})}

缺点是,父组件的状态不会更新。然而,这是标准的设计模式实践,您不应为此依赖父组件数据。