警告:React.memo:比较函数对不相等的 props 返回了 true。这可能导致组件在需要更新时跳过渲染。
Warning: React.memo: The comparison function returned true for props that are not equal. This may cause the component to skip rendering when it should update.
ID: react/memo-wrong-comparison
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.6+ | active | — | — | — |
| React 17.x | active | — | — | — |
| React 18.x | active | — | — | — |
根因分析
传递给 React.memo 的自定义比较函数对实际上不同的 props 错误地返回 true(相等),导致组件在应该更新时跳过了重新渲染。
English
A custom comparison function passed to React.memo incorrectly returns true (equal) for props that are actually different, causing the component to skip re-renders when it should update.
官方文档
https://reactjs.org/docs/react-api.html#reactmemo解决方案
-
Fix the comparison function to correctly compare all relevant props. Example: const MyComponent = React.memo(Comp, (prevProps, nextProps) => { return prevProps.id === nextProps.id && prevProps.name === nextProps.name; }); Ensure it returns false when props differ. -
If the component relies on deep equality, use a library like lodash.isEqual for the comparison: import isEqual from 'lodash.isequal'; React.memo(Comp, isEqual);
-
Remove the custom comparison function and let React.memo use default shallow comparison, but ensure props are immutable references.
无效尝试
常见但无效的做法:
-
70% 失败
Shallow comparison may still miss deep changes, and the warning indicates the custom function is buggy, not that shallow is better.
-
85% 失败
JSON.stringify is slow and can produce false positives for object key order; also triggers the same warning if not careful.
-
65% 失败
Defeats the purpose of memoization and may cause performance issues, but does not fix the underlying logic error.