alibaba / alibaba/hooks

useDeepCompareEffect 存在依赖变更但是不触发的场景

Open
#2,663 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
15k
Forks
2.8k
Avg merge
15h 7m
Merged PRs (30d)
2

Description

复现组件:
```js
function Components() {
const [value, setValue] = useState([
{
label: '1'
}
]);
useDeepCompareEffect(() => {
console.log('触发');
}, [value]);

const handleSearch = (valueStr: string) => {
const newValue = [...value];
// newValue[0].label = valueStr; // 这么写不会触发 useDeepCompareEffect
newValue[0] = { label: valueStr }; // 这么写可以 触发 useDeepCompareEffect
setValue(newValue);
};

const handleClick = () => {
console.log('点击', value);
};

return (


{value.map((item, index) => {
return (

{
handleSearch(e.target.value);
}}
/>
获取

);
})}

);
}
```
本质上是因为ref缓存了之前的对象,如果是通过直接修改对象的值进行的变更,那么在比较的时候,也是拿的最新的已经产生变更的ref进行比较。这样子并不会触发`useDeepCompareEffect` 的回调,可以考虑改成clone快照 使其与外部环境解耦。
https://github.com/alibaba/hooks/blob/c7bb04c42bd8800164a112fd448c263bd16b63d4/packages/hooks/src/createDeepCompareEffect/index.ts#L15

Contributor guide

Open the contributing guide

Research direction

Start in packages/hooks/src/createDeepCompareEffect/index.ts at the referenced comparison logic and reproduce the in-place nested-object mutation shown in the issue. Add a regression test covering that case alongside the existing deep-compare effect tests, then verify that the effect callback runs when the nested value changes.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript
Domain
frontend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.