简体   繁体   English

React 跟踪对象数组更改的最佳方式

[英]React best way to track changes to an array of objects

Say I have an array of objects like this and it is stored in state:假设我有一个这样的对象数组,它存储在 state 中:

interface CheckItem {
  label: string;
  checked: boolean;
  disabled: boolean;
}

const [checkboxes, setCheckboxes] = useState<CheckItem[] | undefined>(undefined);


const checkboxArr: CheckItem[] = [
{label: 'item1', checked: true, disabled: false}, 
{label: 'item2', checked: false, disabled: false}
];

useEffect(() => {
  setCheckboxes(checkboxArr);
}, [])

//should remain disabled until changes are made
//should revert to disabled if changes are undone
<Button disabled={disabled}>Apply Changes</Button>

I also have a button that should remain disabled until one of the original elements has been changed.我还有一个按钮,在更改原始元素之一之前,该按钮应保持禁用状态。

What is the best way to track changes that are made to any property of each element in the array?跟踪对数组中每个元素的任何属性所做的更改的最佳方法是什么? The array can be any length, so I would like to optimize for space/time.数组可以是任意长度,所以我想优化空间/时间。

By what I can understand by your question is you want to know if someone is clicked on the checkbox or not right?根据你的问题我能理解的是你想知道是否有人点击了复选框?

You can simply track changes by having the constant variable that you already created called checkBoxArr and compare it to a new array say tempCheckBoxArr.您可以简单地跟踪更改,方法是让您已经创建的名为 checkBoxArr 的常量变量并将其与新数组(如 tempCheckBoxArr)进行比较。

So say we create an array const [tempCheckBoxArr, setTempCheckBoxArr] = useState<string[]>([])所以说我们创建一个数组const [tempCheckBoxArr, setTempCheckBoxArr] = useState<string[]>([])

This is an empty array and we can store the labels of the items in this array.这是一个空数组,我们可以将项目的标签存储在该数组中。

Now suppose you have an onclick function on the checkboxes.现在假设您在复选框上有一个 onclick function。

So,所以,

checkboxArr.map((checkbox) => {
  return(
      <div>
        <input type="checkbox" checked={checkbox.checked} onClick={() => handleCheckBox(checkbox.label)}/>
      </div>
  )
})

And the function handleCheckBox is:而 function handleCheckBox 是:

const handleCheckBox = (label: string) => {
  if(!tempCheckBoxArr.includes(label)){
    tempCheckBoxArr.push(label)
    setTempCheckBoxArr(tempCheckBoxArr)
  }else{
    let tempArr = tempCheckBoxArr.filter((labelInclude) => labelInclude !== label)
    
    setTempCheckBoxArr(tempArr)
    
  }
}

By the length of the tempCheckBoxArr.length that we created you can then track if your button should be disabled or not and also if there are changes.根据我们创建的tempCheckBoxArr.length的长度,您可以跟踪您的按钮是否应该被禁用以及是否有更改。

Thank you, please feel free to comment if you have questions.谢谢,有问题欢迎留言。

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

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