My Parent component retrieves the checked inputs value from its child component.
(我的父组件从其子组件检索选中的输入值 。)
So I have a function (handleChecked) that takes two parameters : one 'id' and one checked status 'isChecked' :(所以我有一个函数(handleChecked) ,它带有两个参数:一个'id'和一个检查状态'isChecked' :)
const handleChecked = useCallback(({ id, isChecked }) => {
const newCheckedValues = checkedValues.filter(current => current !== id);
setCheckedValues(newCheckedValues);
if (isChecked) {
newCheckedValues.push(id);
setCheckedValues(newCheckedValues);
}
}, [checkedValues]);
What my function is supposed to do :
(我的功能应该做什么:)
1 - Get id and checked status from the clicked input, 2 - Check the state for duplicate id's, 3 - If present, remove it, 4 - Save the state, 5 - If checked, store the id in a temporary array, 6 - Save the new state.
(1-从单击的输入中获取ID和已检查状态,2-检查状态中是否存在重复的ID,3-如果存在,将其删除,4-保存状态,5-如果已检查,将ID存储在临时数组中,6-保存新状态。)
What it does :
(它能做什么 :)
When I click a new input , the parent "checkedValues" state is empty and starts over from nothing.
(当我单击新输入时 ,父“ checkedValues”状态为空,并且从零开始 。)
Meaning that the temporary array created as the result of the filtered state, is also empty.(这意味着作为过滤状态结果创建的临时数组也为空。)
Right now, this function just adds an id in the state, then replace it by the new clicked input.(现在,此函数仅在状态中添加一个id,然后将其替换为新单击的输入。)
And I need to gather all the checked values and store them in the state before sending that to an api later.
(我需要收集所有检查的值 并将它们存储在状态中,然后再将其发送到api。)
I manage to present my "expectations" in this sandbox :(我设法在此沙箱中展示我的“期望”:)
https://codesandbox.io/s/react-hooks-filter-state-array-toggle-input-checked-gz504
(https://codesandbox.io/s/react-hooks-filter-state-array-toggle-input-checked-gz504)
It works, the only difference is it's in the same component and uses html form event and not props legacy .
(它可以工作,唯一的区别是它在同一组件中,并且使用html form事件,而不是props legacy 。)
ask by GonZo translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…