【发布时间】:2020-04-30 13:39:58
【问题描述】:
我有一些可以打开/关闭的开关。它们从父功能组件获得开/关状态。当用户切换状态时,我需要更新父级中的状态并运行一个函数。
该函数使用所有切换的状态来过滤状态中的项目列表,然后更改图形可视化组件中呈现的绘图。
目前,它们切换得很好,但是渲染与按钮的状态不同步,因为处理函数最终以旧状态读取。
我尝试使用 useEffect(),但由于该函数有很多依赖项,因此会导致循环。
我尝试在自定义挂钩中将 useRef() 与 useState() 结合起来,以读出至少设置的最新过滤器组的当前状态,但那里也没有运气。
关于如何以更好的方式重新构建我的代码,或对当前问题的潜在解决方案有什么建议?
进行过滤的总函数:
function filterItems(threshold, items = {}) {
const { values } = kCoreResult;
const { coloredItems } = rgRef.current;
let itemsForUse;
let filteredItems;
if (Object.entries(items).length === 0 && items.constructor === Object) {
itemsForUse = baseItemsRef.current;
} else {
itemsForUse = items;
}
const isWithinThreshold = id => has(values, id) && values[id] >= threshold;
// filter for nodes meeting the kCoreValue criterion plus all links
filteredItems = pickBy(
itemsForUse,
(item, id) => !isNode(item) || isWithinThreshold(id)
);
filteredItems = pickBy(
filteredItems,
item =>
!has(item, 'data.icon_type') || !filterRef.current[item.data.icon_type]
);
setRg(rg => {
rg.filteredItems = leftMerge(filteredItems, coloredItems);
return {
...rg,
};
});
setMenuData(menuData => {
menuData.threshold = threshold;
return {
...menuData,
};
});
}
在按下按钮后调用它的函数也更新按钮状态(按钮状态从过滤器对象向下传递):
function changeCheckBox(id, checked) {
setFilter(filter => {
filter[id] = !checked;
return {
...filter,
};
});
filterItems(menuData.threshold);
}
【问题讨论】:
标签: reactjs react-hooks